c# - LINQ OrderBy 不同字段类型取决于 IF 语句

标签 c# linq sorting

我正在尝试对可能处于以下(推断)状态之一(按此顺序)的一些数据进行排序:

  • live(有效StartDate,空EndDate);
  • 草稿 (null StartDate);
  • ended(有效的 EndDate)。

我在 IQueryable 上继承了以下语法:

iQueryableData
    .OrderBy(t => t.StartDate == null ? 1 : (t.EndDate == null ? 0 : 2))
    .ThenByDescending(t => t.StartDate)
    .ThenBy(t => t.PartnerId)

这很好,因为它根据某些 IF 语句对表的前 3 列之一进行排序。

现在我需要重写它以在不同(但相似)的模型上在内存中工作(所以只有 LINQ,没有 IQueryable)。以下是上述查询将大致转换为的内容:

data
    .OrderBy(t => t.StartDate == null 
                      ? t.EndDate // DateTime
                      : (t.EndDate == null 
                            ? t.Id // integer
                            : t.Name // string
                        )
            )

这显然无法编译,因为

CS0173 C# Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string'

据推测,我可以继续按整数排序,但我不知道在这种情况下数字指的是什么(类中写入的属性的顺序?同一事物的按名称顺序排序? ).

不幸的是,我发现的所有与我相关的问题都是基于依赖于外部值(而不是数据内部)的 IF 语句进行排序。

最佳答案

使用 ThenBy 扩展。这可确保在应用新的订单标准时保持先前的订单。对于每个特定案例,返回所需的属性以按顺序(名称、Id、结束日期)参与,以便集合中的每个组将按这些值排序。对不符合原始条件的其他项目使用一些常量值,以便它们的顺序在当前 ThenBy 中保持不变。

    items
    //sort by live, draft and ended
 .OrderBy(t => t.StartDate == null ? 1 : (t.EndDate == null ? 0 : 2)) 
        //keep the live, draft and ended sort,
        //and for the live items  apply only a sort by ID, 
        //but let the other items in the previous order (live, draft and ended) 
        //by returning the same value for each (zero or null)
    .ThenBy( t=> t.StartDate != null && t.EndDate == null ? t.ID : 0) 
            //the same
            //keep the sort by live, draft, ended and now by ID for live ones only
            //but for the draft items sort them by EndDate
            //leave the others unaffected by this sort
        .ThenBy( t=> t.StartDate == null && t.EndDate != null ? t.EndDate : default(DateTime?))
                //same - sort ended items by name
            .ThenBy( t=> t.StartDate != null && t.EndDate != null ? t.Name : null)

关于c# - LINQ OrderBy 不同字段类型取决于 IF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40586659/

相关文章:

C# 从 LINQ 计算对象初始化期间的日期时间差异

c# - SQL Linq 预留可用性

java - 使用带有自定义比较器的优先级队列根据字符串中的单词数进行排序?

javascript - knockout js和排序问题

c# - 在 .NET 4 中最大化窗口时,窗口顶部和左侧值未正确更新

c# - 打印按钮在 ReportViewer 中不可见

c# - 在 Internet Explorer 实例中运行 JavaScript 函数

c# - 在 Nuget 包中公开 Azure Functions

c# - 在 C# 中,将值感染\传输到列表的相邻项

python - Pandas:对列类别中的每一行进行排序/百分位数