gpt4 book ai didi

c# - 如何动态添加降序到orderby?

转载 作者:太空狗 更新时间:2023-10-29 21:44:07 30 4
gpt4 key购买 nike

我可以使用 orderby 语句动态构造 Linq 查询,如下所示:

var Query = from q in Db.TblUsers select q;

switch (Order)
{
case "Name": Query = from q in Query orderby q.Name select q; break;
case "DOB": Query = from q in Query orderby q.DOB select q; break;
// ... and more cases
}

var Result = Query.ToList();

但是,如果需要降序排列(取决于用户在 UI 中的选择),我将不得不构造另一个 switch 语句来复制所有情况,只是在 orderby 之后添加“降序”关键字。

例子:

if (ascending)
{
switch (Order)
{
case "Name": Query = from q in Query orderby q.Name select q; break;
// ....
}
}
else
{
switch (Order)
{
case "Name": Query = from q in Query orderby q.Name descending select q; break;
// ....
}
}

有没有办法让我动态地向查询添加降序关键字?

最佳答案

给定:

public static class OrderByEx
{
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, bool ascending)
{
if (ascending)
{
return source.OrderBy(keySelector);
}

return source.OrderByDescending(keySelector);
}
}

您可以:

var Query = Db.TblUsers.AsQueryable();

switch (Order)
{
case "Name":
Query = Query.OrderBy(q=>q.Name, ascending);
break;
case "DOB":
Query = Query.OrderBy(q=>q.DOB, ascending);
break;
// ... and more cases
}

关于c# - 如何动态添加降序到orderby?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30961757/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com