2011-09-01 66 views
57

如何使用我将其作为参数的值指定传递给orderby的参数?如何动态指定Linq OrderBy参数?

例:

List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}} 

目前执行:

List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList(); 

相反的c.Address,我怎么可以把它看作一个参数?

string param = "City"; 
List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList(); 
+2

你可能会寻找Dynamic Linq:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx – BrokenGlass

+0

@Nev_Rahd:试图澄清这个问题。另外,'OrderBy'是一个Linq特性,并且在'IEnumerable'上,而不是'List'特有的特性。随意滚动编辑或进一步更改:) –

+0

[动态LINQ OrderBy在IEnumerable ](http:// stackoverflow。com/questions/41244/dynamic-linq-orderby-on-ienumerablet) –

回答

92

下面是使用反射成为了可能......

var param = "Address";  
var propertyInfo = typeof(Student).GetProperty(param);  
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null)); 
+0

这就是我正在寻找的。遗漏了原始答案中的.GetValue部分。 – tsells

+0

这是一个awsm代码...谢谢你,它帮了我很多。 – Harsha

+2

但是,当涉及由供应商解释的Linq表达式时,例如实体框架(sql server或其他)呢? –

1

这不会让你通过一个string,当你问你的问题,但它仍然会为你工作。

OrderByDescending方法采用Func<TSource, TKey>,所以你可以重写你的函数是这样的:

List<Student> QueryStudents<TKey>(Func<Student, TKey> orderBy) 
{ 
    return existingStudents.OrderByDescending(orderBy).ToList(); 
} 

还有其他重载OrderByDescending以及该采取Expression<Func<TSource, TKey>>,和/或IComparer<TKey>。你也可以看看这些,看看他们是否提供任何使用。

+0

这不起作用,因为你没有定义TKey的类型。您必须将您的更改为。 –

+0

@PatrickDesjardins - 那更好? –

+0

这只是对我有用!我想要一个函数,可以根据传递的布尔值来升序或降序排列列表。你的代码很好地调整了一下! –

67

您可以使用反射的一点点构建表达式树如下(这是一个扩展方法):

public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, 
          bool desc) 
{ 
    string command = desc ? "OrderByDescending" : "OrderBy"; 
    var type = typeof(TEntity); 
    var property = type.GetProperty(orderByProperty); 
    var parameter = Expression.Parameter(type, "p"); 
    var propertyAccess = Expression.MakeMemberAccess(parameter, property); 
    var orderByExpression = Expression.Lambda(propertyAccess, parameter); 
    var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, 
            source.Expression, Expression.Quote(orderByExpression)); 
    return source.Provider.CreateQuery<TEntity>(resultExpression); 
} 

orderByProperty是你想,如果订购的属性名传递true作为参数对于desc,将按降序排列;否则,将按升序排序。

现在,你应该能够做到existingStudents.OrderBy("City",true);existingStudents.OrderBy("City",false);

+6

这个答案很棒,比反思的答案好得多。这实际上适用于其他提供者,如实体框架。 – Sam

+0

这太好了。谢谢。 – Saragis

+1

如果可以的话,我会投票给这十次!你在哪里学习写这样的扩展方法?!! – Jach

4
private Func<T, object> GetOrderByExpression<T>(string sortColumn) 
    { 
     Func<T, object> orderByExpr = null; 
     if (!String.IsNullOrEmpty(sortColumn)) 
     { 
      Type sponsorResultType = typeof(T); 

      if (sponsorResultType.GetProperties().Any(prop => prop.Name == sortColumn)) 
      { 
       System.Reflection.PropertyInfo pinfo = sponsorResultType.GetProperty(sortColumn); 
       orderByExpr = (data => pinfo.GetValue(data, null)); 
      } 
     } 
     return orderByExpr; 
    } 

    public List<T> OrderByDir<T>(IEnumerable<T> source, string dir, Func<T, object> OrderByColumn) 
    { 
     return dir.ToUpper() == "ASC" ? source.OrderBy(OrderByColumn).ToList() : source.OrderByDescending(OrderByColumn).ToList();`` 
    } 

// Call the code like below 
     var orderByExpression= GetOrderByExpression<SearchResultsType>(sort); 

    var data = OrderByDir<SponsorSearchResults>(resultRecords, SortDirectionString, orderByExpression);  
+1

可能很好解释这个? –

+0

辉煌!正是我需要的。 –

4

这里的东西我想出了对付有条件降序。您可以将其与其他动态生成keySelector func的方法结合使用。

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, 
      System.Linq.Expressions.Expression<Func<TSource, TKey>> keySelector, 
      System.ComponentModel.ListSortDirection sortOrder 
      ) 
    { 
     if (sortOrder == System.ComponentModel.ListSortDirection.Ascending) 
      return source.OrderBy(keySelector); 
     else 
      return source.OrderByDescending(keySelector); 
    } 

用法:

//imagine this is some parameter 
var direction = System.ComponentModel.ListSortDirection.Ascending; 
query = query.OrderBy(ec => ec.MyColumnName, direction); 

注意这允许您链这个.OrderBy扩展了新的参数到任何IQueryable的。

// perhaps passed in as a request of user to change sort order 
// var direction = System.ComponentModel.ListSortDirection.Ascending; 
query = context.Orders 
     .Where(o => o.Status == OrderStatus.Paid) 
     .OrderBy(ec => ec.OrderPaidUtc, direction); 
1

是为我工作在这里https://gist.github.com/neoGeneva/1878868通过neoGeneva发布的唯一解决方案。

我会重新发布他的代码,因为它运行良好,我不希望它在网页中丢失!

public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortExpression) 
    { 
     if (source == null) 
      throw new ArgumentNullException("source", "source is null."); 

     if (string.IsNullOrEmpty(sortExpression)) 
      throw new ArgumentException("sortExpression is null or empty.", "sortExpression"); 

     var parts = sortExpression.Split(' '); 
     var isDescending = false; 
     var propertyName = ""; 
     var tType = typeof(T); 

     if (parts.Length > 0 && parts[0] != "") 
     { 
      propertyName = parts[0]; 

      if (parts.Length > 1) 
      { 
       isDescending = parts[1].ToLower().Contains("esc"); 
      } 

      PropertyInfo prop = tType.GetProperty(propertyName); 

      if (prop == null) 
      { 
       throw new ArgumentException(string.Format("No property '{0}' on type '{1}'", propertyName, tType.Name)); 
      } 

      var funcType = typeof(Func<,>) 
       .MakeGenericType(tType, prop.PropertyType); 

      var lambdaBuilder = typeof(Expression) 
       .GetMethods() 
       .First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2) 
       .MakeGenericMethod(funcType); 

      var parameter = Expression.Parameter(tType); 
      var propExpress = Expression.Property(parameter, prop); 

      var sortLambda = lambdaBuilder 
       .Invoke(null, new object[] { propExpress, new ParameterExpression[] { parameter } }); 

      var sorter = typeof(Queryable) 
       .GetMethods() 
       .FirstOrDefault(x => x.Name == (isDescending ? "OrderByDescending" : "OrderBy") && x.GetParameters().Length == 2) 
       .MakeGenericMethod(new[] { tType, prop.PropertyType }); 

      return (IQueryable<T>)sorter 
       .Invoke(null, new object[] { source, sortLambda }); 
     } 

     return source; 
    } 
4

1)安装System.Linq.Dynamic

2)添加以下代码

public static class OrderUtils 
{ 
    public static string ToStringForOrdering<T, TKey>(this Expression<Func<T, TKey>> expression, bool isDesc = false) 
    { 
     var str = expression.Body.ToString(); 
     var param = expression.Parameters.First().Name; 
     str = str.Replace("Convert(", "(").Replace(param + ".", ""); 
     return str + (isDesc ? " descending" : ""); 
    } 
} 

3)撰写您的开关lambda函数

public static class SortHelper 
{ 
    public static Expression<Func<UserApp, object>> UserApp(string orderProperty) 
    { 
     orderProperty = orderProperty?.ToLowerInvariant(); 
     switch (orderProperty) 
     { 
      case "firstname": 
       return x => x.PersonalInfo.FirstName; 
      case "lastname": 
       return x => x.PersonalInfo.LastName; 
      case "fullname": 
       return x => x.PersonalInfo.FirstName + x.PersonalInfo.LastName; 
      case "email": 
       return x => x.Email; 

     } 
    } 
} 

4的选择)使用你的助手

Dbset.OrderBy(SortHelper.UserApp("firstname").ToStringForOrdering()) 

5)您可以用pagging(PagedList

public virtual IPagedList<T> GetPage<TOrder>(Page page, Expression<Func<T, bool>> where, Expression<Func<T, TOrder>> order, bool isDesc = false, 
     params Expression<Func<T, object>>[] includes) 
    { 
     var orderedQueryable = Dbset.OrderBy(order.ToStringForOrdering(isDesc)); 
     var query = orderedQueryable.Where(where).GetPage(page); 
     query = AppendIncludes(query, includes); 

     var results = query.ToList(); 
     var total = Dbset.Count(where); 

     return new StaticPagedList<T>(results, page.PageNumber, page.PageSize, total); 
    } 

说明使用

System.Linq.Dynamic使我们能够在排序依据的方法设置字符串值。但是在这个扩展中,字符串将被解析为Lambda。所以我认为它会工作,如果我们将解析Lambda字符串并将其提供给OrderBy方法。它的工作原理!

0

我很晚参加聚会,但这些解决方案都不适合我。我急于尝试System.Linq.Dynamic,但我无法在Nuget上找到它,也许折旧?无论哪种方式......

这是我想出的解决方案。我需要动态使用OrderBy,OrderByDescendingOrderBy> ThenBy

我简单地为我的列表对象创建了一个扩展方法,我知道有一点哈克...我不会推荐这个,如果这是我做了很多事情,但它对一个好的东西是好的。

List<Employee> Employees = GetAllEmployees(); 

foreach(Employee oEmployee in Employees.ApplyDynamicSort(eEmployeeSort)) 
{ 
    //do stuff 
} 

public static IOrderedEnumerable<Employee> ApplyDynamicSort(this List<Employee> lEmployees, Enums.EmployeeSort eEmployeeSort) 
{ 
    switch (eEmployeeSort) 
    { 
     case Enums.EmployeeSort.Name_ASC: 
      return lEmployees.OrderBy(x => x.Name); 
     case Enums.EmployeeSort.Name_DESC: 
      return lEmployees.OrderByDescending(x => x.Name); 
     case Enums.EmployeeSort.Department_ASC_Salary_DESC: 
      return lEmployees.OrderBy(x => x.Department).ThenByDescending(y => y.Salary); 
     default: 
      return lEmployees.OrderBy(x => x.Name); 
    } 
} 
0
  • 炸药添加金块包到您的代码

  • 添加命名空间Dynamite.Extensions 例如:使用Dynamite.Extensions;

  • 通过查询为任意SQL查询提供排序 例如:students.OrderBy(“City DESC,Address”)。ToList();

0

为了扩大在answer by @Icarus:如果你想扩展方法的返回类型是一个IOrderedQueryable而不是一个IQueryable,你可以简单地把结果如下:

public static IOrderedQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc) 
{ 
    string command = desc ? "OrderByDescending" : "OrderBy"; 
    var type = typeof(TEntity); 
    var property = type.GetProperty(orderByProperty); 
    var parameter = Expression.Parameter(type, "p"); 
    var propertyAccess = Expression.MakeMemberAccess(parameter, property); 
    var orderByExpression = Expression.Lambda(propertyAccess, parameter); 
    var resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { type, property.PropertyType }, 
     source.Expression, Expression.Quote(orderByExpression)); 
    return (IOrderedQueryable<TEntity>)source.Provider.CreateQuery<TEntity>(resultExpression); 
}