带有布尔值的多orderby linq查询

本文关键字:orderby linq 查询 布尔值 | 更新日期: 2023-09-27 18:19:32

假设我有一个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>
}

我希望能够通过这些布尔值进行排序或筛选。但并非所有属性都是必需的。因此,有些是可以为null的。我想构建一个动态查询,简单地将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);
         }
      }
  }

我不知道如何做到这一点。也许有更简单的方法??

带有布尔值的多orderby linq查询

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

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