Access nested properties with dynamic lambda using Linq.Expression

前端 未结 4 2506
说谎
说谎 2021-02-20 10:39

Let\'s assume that I have two classes:

class person
{
    int ID
    string name
    Address address
}
class address
{
    int ID
    string street
    string co         


        
4条回答
  •  死守一世寂寞
    2021-02-20 11:22

    Try this one

        public static IQueryable SortIQueryable(IQueryable data, string fieldName, string sortOrder)
        {
            if (string.IsNullOrWhiteSpace(fieldName)) return data;
            if (string.IsNullOrWhiteSpace(sortOrder)) return data;
    
            var param = Expression.Parameter(typeof(T), "i");
    
            MemberExpression property = null;
            string[] fieldNames = fieldName.Split('.');
            foreach (string filed in fieldNames)
            {
                if (property == null)
                {
                    property = Expression.Property(param, filed);
                }
                else
                {
                    property = Expression.Property(property, filed);
                }
            }
    
            Expression conversion = Expression.Convert(property, typeof(object));//Expression.Property(param, fieldName)
            var mySortExpression = Expression.Lambda>(conversion, param);
    
            return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
                : data.OrderBy(mySortExpression);
        }
    

提交回复
热议问题