Sorting using lamba expression

Total Post:183

 1308  View(s)
Rate this:

I am trying to Sort Users Using lambda Expression. My Users class

public class Users
        public long Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateCreated { get; set; }

And My Sorting method

public List<Users> SortUsers(string sSortBy)
    var arg = Expression.Parameter(typeof(Users), "Users");
    var body = Expression.Convert(Expression.Property(arg, sSortBy), typeof(object));
    var lambda = Expression.Lambda<Func<Users, object>>(body, arg);
    List<Users> UserList;
    UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList(); // Error here
    return UserList;

I am Accessing the method by

List<Users> UserList;

UserList = objUsers.SortUsers("FirstName");

I am passing sSortBy as string (here "FirstName")

Error :Unable to cast the type 'System.String' to type 'System.Object'.

Comes in line UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList();

  1. Post:412

    Re: Sorting using lamba expression

    Hi Ankita,

    public static List<Users> SortUsers(string sSortBy)
        var arg =Expression.Parameter(typeof(Users), "Users");
        var sortProperty =Expression.Property(arg, sSortBy);
        var lambda =Expression.Lambda(sortProperty, arg);
        var param =Expression.Parameter(typeof(IQueryable<Users>));
        var orderByCall =Expression.Call(typeof(Queryable), "OrderBy", new Type[] { typeof(Users), sortProperty.Type }, new Expression[] { param, lambda });
        var orderLambda =Expression.Lambda<Func<IQueryable<Users>, IQueryable<Users>>>(orderByCall, param).Compile();
        List<Users> UserList;
        UserList =orderLambda(UOWUser.UsersRepository.Entities).ToList(); // Error here
        return UserList;

    It makes the entire source.OrderBy(x => x.PropName) through Expression, so you don't have to actually specify x.PropName type.

      Modified On Apr-04-2018 04:43:23 AM