Linq 从字符串排序方向

发布于 2024-08-05 22:51:13 字数 637 浏览 3 评论 0原文

我正在尝试对一组用户进行排序。我可以访问排序属性和方向(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;
}

I am trying to sort a set of Users. I have access to the sorting property and direction (asc, desc). My current order by query is below. But as you can see it doesn't account for the sort direction. How do can I build this expression without having to use Dynamic Linq, or adding another set of statements for "asc" or "desc" sort direction.

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吃兔兔 2024-08-12 22:51:13

理想情况下,您想要使用 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 传递选择器和布尔值?

如果您不需要静态类型,当然也可以从头开始动态构建表达式 - 就像 这个简短的示例(本质上与动态 LINQ 库类似)。

Ideally, you want to use OrderByDescending - you could of course cheat:

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); 
    }
}

And use OrderBy passing in the selector and a bool?

If you don't need the static typing, you can also build the expressions dynamically from the ground up, of course - like this short sample (similar in nature to the dynamic LINQ library).

人间☆小暴躁 2024-08-12 22:51:13

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

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

也看看这个: 使用 Lambda/Linq to 对象对列表进行排序

It'd be an if statement I think, no other simple way to do it, i.e.:

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

Have a look at this as well: Sorting a list using Lambda/Linq to objects

终陌 2024-08-12 22:51:13

查看 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);
    }

但请务必检查用户输入!

Have a look at the CS Code Samples. There are a dynamic Linq examples.

From the samples:

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)");

Order by Code:

    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);
    }

But be sure that you check User Input!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文