Dynamically Sorting with LINQ

后端 未结 9 2019
自闭症患者
自闭症患者 2020-12-16 04:57

I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name

9条回答
  •  攒了一身酷
    2020-12-16 05:52

    You will need to use reflection to get the PropertyInfo, and then use that to build an expression tree. Something like this:

    var entityType = typeof(TEntity);
    var prop = entityType.GetProperty(sortProperty);
    var param = Expression.Parameter(entityType, "x");
    var access = Expression.Lambda(Expression.MakeMemberAccess(param, prop), param);
    
    var ordered = (IOrderedQueryable) Queryable.OrderBy(
        myCollection, 
        (dynamic) access);
    

提交回复
热议问题