Order a list by a property name(string value)?

前端 未结 2 1961
余生分开走
余生分开走 2020-12-28 10:45

I have a list of objects. How can I order this list using property name?

string orderbyField = \"Code\";
List l = FillList();
l =          


        
      
      
      
2条回答
  •  无人及你
    2020-12-28 11:11

    Order by property name without type reflection

        public static class IQueryableExtensions
        {
          public static IQueryable OrderBy(this IQueryable source, string 
          propertyName)
          {
          return (IQueryable)OrderBy((IQueryable)source, propertyName);
          }
    
          public static IQueryable OrderBy(this IQueryable source, string propertyName)
          {
            var x = Expression.Parameter(source.ElementType, "x");
            var body = propertyName.Split('.').Aggregate(x, 
            Expression.PropertyOrField);
    
            var selector = Expression.Lambda
             (Expression.PropertyOrField(x, propertyName), x);
    
             return source.Provider.CreateQuery(
                Expression.Call(typeof(Queryable), "OrderBy", new Type[] { 
                 source.ElementType, selector.Body.Type },
                     source.Expression, selector
                     ));
          }
    
          public static IQueryable OrderByDescending(this IQueryable source, 
          string propertyName)
          {
            return (IQueryable)OrderByDescending((IQueryable)source, propertyName);
          }
    
          public static IQueryable OrderByDescending(this IQueryable source, string 
          propertyName)
          {
            var x = Expression.Parameter(source.ElementType, "x");
            var selector = Expression.Lambda(Expression.PropertyOrField(x, 
            propertyName),x);
            return source.Provider.CreateQuery(
                Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { 
                 source.ElementType, selector.Body.Type },
                     source.Expression, selector
                     ));
          }
    }
    

提交回复
热议问题