2

I need to set the key in the OrderBy clause using linq , where the key is a property of an object. I only have the property name with me. How can i set the property dynamically.

class Obj 
{
    string Level
    {
       get;
       set;
    }
}

List<Obj> objList;

objList.OrderByDescending(x => x.Level); => "here i only have property name."

Hope any one can help

Thanks Sunil

4

1 に答える 1

5

これは、拡張メソッドと動的に式ツリーを作成することで実行できます

public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> enumerable, string sortColumn)
{
    var param = Expression.Parameter(typeof(T), "x");
    var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);
    return enumerable.OrderByDescending(mySortExpression);;
 }

および OrderBy の場合

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> enumerable, string sortColumn)
{
    var param = Expression.Parameter(typeof(T), "x");
    var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);
    return enumerable.OrderBy(mySortExpression);;
 }

これら2つを1つのように組み合わせることができます

public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> enumerable, string sortColumn, string direction)
{
     var param = Expression.Parameter(typeof(T), "x");
     var mySortExpression = Expression.Lambda<Func<T, object>>(Expression.Property(param, sortColumn), param);

      IOrderedQueryable<T> iQuery;
      switch(direction)
      {
          case "desc": 
            iQuery = enumerable.OrderByDescending(mySortExpression);
            break;
          case "asc":
          default :
            iQuery = enumerable.OrderBy(mySortExpression);
            break;
      }
      return iQuery;
 }

objList.OrderBy("Level","asc")次に、 //For Ascending objList.OrderBy("Level","desc")//For Descendingのように呼び出すことができます

それが役立つことを願っています

于 2012-09-24T11:59:17.213 に答える