在 LINQ 中升序/降序 - 可以通过参数更改顺序吗? [英] ascending/descending in LINQ - can one change the order via parameter?

查看:22
本文介绍了在 LINQ 中升序/降序 - 可以通过参数更改顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,它的参数是bool sortAscending".现在我想使用 LINQ 根据此参数创建排序列表.然后我得到了这个:

I have a method which is given the parameter "bool sortAscending". Now I want to use LINQ to create sorted list depending on this parameter. I got then this:

var ascendingQuery = from data in dataList
                      orderby data.Property ascending
                      select data;

var descendingQuery = from data in dataList
                      orderby data.Property descending
                      select data;

如您所见,两个查询仅在升序"方面有所不同.下降".我想合并两个查询,但我不知道如何.有人有答案吗?

As you can see, both queries differ only in "ascending" resp. "descending". I'd like to merge both queries, but I don't know how. Does anyone have the answer?

推荐答案

您可以轻松地在 IEnumerable 或 IQueryable 上创建自己的扩展方法:

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

是的,您在这里失去了使用查询表达式的能力 - 但坦率地说,我认为在这种情况下您实际上并没有从查询表达式中受益.查询表达式非常适合处理复杂的事情,但如果您只执行一项操作,则只执行一项操作会更简单:

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

这篇关于在 LINQ 中升序/降序 - 可以通过参数更改顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆