Home > DeveloperSection > Forums > Sorting using lamba expression
Ankita Pandey
Ankita Pandey

Total Post:183

Posted on    March-26-2014 4:02 AM

 C# C# 

 1 Reply(s)
 929  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();

Pravesh Singh

Total Post:412

Posted on    March-26-2014 4:34 AM

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.

Don't want to miss updates? Please click the below button!

Follow MindStick