0

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)

1 Answer 1

1

There's a much simpler solution to this, just use the fluent interface of LINQ:

var query = context.Users.AsQueryable();

switch (userOrder)
{
    case UserOrder.RegistDate:
        query = query.Orderby(a => a.RegistrationDate);
        break;
    case UserOrder.A_Z:
        query = query.Orderby(a => a.UserName);
        break;
    case UserOrder.Z_A:
        query = query.OrderbyDescending(a => a.UserName);
        break;
    case UserOrder.MostComment:
        query = query.Orderby(a => a.Comments.Count);
        break;
}

IEnumerable<AppUser> results = query
    .Select(a => new AppUser
    {
        UserName = a.UserName,
        Id = a.Id,
        Email = a.Email,
        EmailConfirmed = a.EmailConfirmed,
        RegistrationDate = a.RegistrationDate
    })
    .ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but i just have to use var query = context.Users.AsQueryable() instead of var query = context.Users
@mustafa I forgot that AsQueryable was needed (depends on the EF version), fixed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.