Linq从字符串排序方向

时间:2009-09-29 15:21:33

标签: c# linq linq-to-sql sorting sortdirection

我正在尝试对一组用户进行排序。我可以访问排序属性和方向(asc,desc)。我目前的查询订单如下。但正如您所看到的那样,它并未考虑排序方向。如何在不必使用Dynamic Linq或为“asc”或“desc”排序方向添加另一组语句的情况下构建此表达式。

public override IQueryable<DalLinq.User> GetSort(IQueryable<DalLinq.User> query) 
{
    //SelectArgs.SortDirection <- Sort Direction
    switch (SelectArgs.SortProperty) 
    {
      case "LastName":
        query = query.OrderBy(p => p.LastName);
        break;
      case "FirstName":
        query = query.OrderBy(p => p.FirstName);
        break;
      default:
        query = query.OrderBy(p => p.UserName);
        break;
    } 

    return query;
}

3 个答案:

答案 0 :(得分:12)

理想情况下,您想使用OrderByDescending - 您当然可以作弊:

public static class MyExtensionMethods 
{
    public static IOrderedQueryable<TSource> OrderBy<TSource,TValue>(
        this IQueryable<TSource> source,
        Expression<Func<TSource,TValue>> selector,
        bool asc) 
    {
        return asc ? source.OrderBy(selector) : source.OrderByDescending(selector); 
    }
}

使用OrderBy传递选择器和bool?

如果你不需要静态类型,你也可以从头开始动态构建表达式 - 当然像this short sample(与动态LINQ库类似)。

答案 1 :(得分:2)

我认为这是一个if语句,没有其他简单的方法可以做到,即:

query = (SelectArgs.SortDirection == "asc") ? query.OrderBy(p => p.LastName)
          : query.OrderByDescending(p => p.LastName);

也请看一下:Sorting a list using Lambda/Linq to objects

答案 2 :(得分:0)

查看CS代码示例。有一个动态的Linq例子。

来自样本:

Northwind db = new Northwind(connString); 
db.Log = Console.Out;

var query =
  db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
  OrderBy("CompanyName").
  Select("New(CompanyName as Name, Phone)");

按代码订购:

    public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) {
        return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
    }

    public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
        if (source == null) throw new ArgumentNullException("source");
        if (ordering == null) throw new ArgumentNullException("ordering");
        ParameterExpression[] parameters = new ParameterExpression[] {
            Expression.Parameter(source.ElementType, "") };
        ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
        IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
        Expression queryExpr = source.Expression;
        string methodAsc = "OrderBy";
        string methodDesc = "OrderByDescending";
        foreach (DynamicOrdering o in orderings) {
            queryExpr = Expression.Call(
                typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
                new Type[] { source.ElementType, o.Selector.Type },
                queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
            methodAsc = "ThenBy";
            methodDesc = "ThenByDescending";
        }
        return source.Provider.CreateQuery(queryExpr);
    }

但请务必检查用户输入!