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

标签 c# linq sql-order-by tuples

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

相关文章:

c# - Linq 用 OR 动态追加 Where 子句

mysql - 为什么分组依据和排序依据给出 0 响应

mysql - 如何对 MySQL 的 varchar 值进行排序

sql - 3级嵌套排序

c# - "kill"background worker怎么彻底?

c# - LINQ 查询返回是否在数组中找到一个项目?

c# - 将 NHibernate ISession.Get<>() 与复合键一起使用

c# - 在这种情况下我将如何使用 LINQ2XML?

c# - 是否可以将单个 linq 查询结果分配给多个变量?

c# - 简洁、快速的单例子类