gpt4 book ai didi

c# - 动态 Linq 按变量排序

转载 作者:行者123 更新时间:2023-12-04 12:50:24 26 4
gpt4 key购买 nike

我有一个表,我正在为其编写一些 C# selenium 自动化,需要一些使用 Dynamic Linq 的帮助。假设我有一个基本的 AcctNumAcctDateAcctName 记录,每个字段都可以由用户排序。他们可以选择 AcctNum (asc)、AcctDate(asc),最后选择 AcctName (asc)。

那就是:

 var sortedCode = records.OrderBy(r => r.AcctNum)
.ThenBy(r => r.AcctDate)
.ThenBy(r => r.AcctName)
.ToList();

但是用户也可以选择 AcctNum (desc),AcctDate(asc) 最后是 AcctName (desc)。

我想做的是使用 Dynamic Linq 并使每个排序顺序成为一个变量。

所以像这样:

 //passed in values:
var varAcctNumOrd = "desc";
var varDateOrd = "asc";
var varAcctOrd = "desc";

var sortedCode = records.OrderBy(r => r.AcctNum, varAcctNumOrd)
.ThenBy(r => r.AcctDate, varDateOrd)
.ThenBy(r => r.AcctNum, varAcctOrd)
.ToList();

这可能吗?

最佳答案

如果我理解正确,下面简单的自定义扩展方法应该可以完成这项工作:

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

public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(
this IOrderedEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool ascending)
{
return ascending ? source.ThenBy(keySelector) : source.ThenByDescending(keySelector);
}

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

public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(
this IOrderedQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool ascending)
{
return ascending ? source.ThenBy(keySelector) : source.ThenByDescending(keySelector);
}
}

用法将是:

//passed in values:
var varAcctNumOrd = "desc";
var varDateOrd = "asc";
var varAcctOrd = "desc";

var sortedCode = records.OrderBy(r => r.AcctNum, varAcctNumOrd != "desc")
.ThenBy(r => r.AcctDate, varDateOrd != "desc")
.ThenBy(r => r.AcctNum, varAcctOrd != "desc")
.ToList();

关于c# - 动态 Linq 按变量排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733447/

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