gpt4 book ai didi

c# - 使用 bool 值的多个 orderby linq 查询

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:43 26 4
gpt4 key购买 nike

假设我有一个 CustomObjects 列表

List<CustomObject> list = new List<CustomObject>();
public class CustomObject
{
public int page {get;set;}
public bool configured {get;set;}
public bool searchable {get;set;}
<more bool properties>
}

并且我希望能够按这些 bool 值进行排序或过滤。但并非所有属性都是必需的。所以,有些可以为空。我想构建一个简单地将 OrderBy() 和 ThenBy() 链接在一起的动态查询我想也许我应该创建一个元组来提供帮助。

List<Tuple<string, bool>> expressionTuple = new List<Tuple<string, bool>>();
// so now I have a list of tuples.
// so based on whether or not my method parameters are null or not I populate the list
if(ShouldFilter(methodParameter))
{
expressionTuple.Add(new Tuple<string, bool>("ColumnName", methodParameter)));
}

所以我在考虑某种链式自定义排序函数,如下所示:

private IEnumerable<T> CustomSort<T>(IEnumerable<T> data, List<Tuple<string, bool>> sortExpression)
{
for(int i = 0; i < sortExpression.Count; i++)
{
int index = i; // see if this is the first iteration
// build an expression that would be similar to:
if(index==0)
{
data = list.OrderBy(x=>x.ColumnName == booleanValue);
}else
{
data = list.ThenBy(x=>x.ColumnNam == booleanValue);
}
}
}

我不确定如何完成此操作。也许有更简单的方法??

最佳答案

为什么?如果您在不同的地方使用不同的顺序,只需将 LINQ 表达式放在这些不同的地方?在我看来,您似乎是在试图将其实并不那么复杂的事情复杂化。

data.OrderBy(p => p.Page)
.ThenBy(p => p.Configured)
.ThenBy(...);

关于c# - 使用 bool 值的多个 orderby linq 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25510971/

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