作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试对可能处于以下(推断)状态之一(按此顺序)的一些数据进行排序:
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/
我是一名优秀的程序员,十分优秀!