我有一个方法,它的参数是“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/