LINQ顺序不同的字段类型取决于IF语句
本文关键字:类型 取决于 IF 语句 字段 顺序 LINQ | 更新日期: 2023-09-27 18:17:43
我正在尝试排序一些可以在以下(推断)状态之一的数据(按此顺序):
-
live
(有效StartDate
,无效EndDate
); -
draft
(nullStartDate
); -
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#不能确定条件表达式的类型,因为'int'和'string'之间没有隐式转换
假设,我可以继续按整数排序,但我不知道在这种情况下数字指的是什么(属性的顺序写在类内?
不幸的是,我发现与我相关的所有问题都是基于依赖于外部值(而不是数据内部)的IF
语句的排序。
使用ThenBy扩展名。这可以确保在应用新订单标准时保持先前的订单。对于每个特定的情况,按顺序返回所需的属性(Name、Id、EndDate),以便集合中的每个组将按这些值排序。对其他不符合原始条件的项目使用一些常量值,以便它们的顺序在当前的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)
我建议您为您的数据实现比较器。compareTo方法将处理一些复杂的情况,你可能有:如果linq必须比较日期,数字或字符串怎么办?