c# - LINQ 中的升序/降序 - 可以通过参数更改顺序吗?

标签 c# linq

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

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

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

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

最佳答案

您可以轻松地在 IEnumerable 或 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);
}

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

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

关于c# - LINQ 中的升序/降序 - 可以通过参数更改顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50860824/

相关文章:

linq - C# Linq SelectMany,返回整个对象

c# - 在 Linq 中选择 column1 的所有不同的最后记录并按 column2 排序(相应地不工作)

c# - 如何掌握所有C#函数特性?

c# - 使用 TimeSpan.FromTicks 延迟任务是否正确?

c# - 在同一项目中结合 Authorization.Forms 和 Authorization.Token 的最佳方法?

c# - 如何刷新图片框

c# - 为什么这种反向阵列方法不起作用?

c# - 如何使用远程数据将超链接配置到我的 Kendo UI TreeView 中?

c# - 在 C# 中比较可能为空的字符串

c# - LINQ to SQL 在更新后返回旧数据