I want to get data from database ordered by something that i choose it, as example, i want to get all Users registered in website ordered by: Name, Name ascending, Register Date, or Number of comments.
I do not want to repeat all select statement because of only order by statement
that is my code but it not work with me:
Expression<Func<AppUser, Object>> OrderByExpression = null;
switch (userOrder)
{
case UserOrder.RegistDate:
OrderByExpression = a => a.RegistrationDate;
break;
case UserOrder.A_Z:
OrderByExpression = a => a.UserName;
break;
case UserOrder.Z_A:
OrderByExpression = a => a.UserName descending;
break;
case UserOrder.MostComment:
OrderByExpression = a => a.Comments.Count;
break;
}
That is Select statement:
IEnumerable<AppUser> AllUsers =
(from a in context.Users
orderby OrderByExpression.Compile()(a)
select new AppUser
{
UserName = a.UserName,
Id = a.Id,
Email = a.Email,
EmailConfirmed = a.EmailConfirmed,
RegistrationDate = a.RegistrationDate
}).ToList();
It work fine but the problem when i want to order by Comments.Count & UserName descending, the problem is in (Count & descending)