gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:40:50 27 4
gpt4 key购买 nike

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

  • 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/

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