上升/在LINQ降 - 可以在一个修改通过参数的顺序? [英] ascending/descending in LINQ - can one change the order via parameter?

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

问题描述

我有被赋予参数布尔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;



正如你可以看到,这两个查询只有在升序RESP不同。 降。我想合并这两个查询,但我不知道怎么办。 ?有没有人有答案

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天全站免登陆