加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ OrderBy根据IF语句的不同字段类型

发布时间:2020-12-15 22:37:26 所属栏目:百科 来源:网络整理
导读:我正在尝试排序一些可以处于以下(推断)状态之一的数据(按此顺序): live(有效的StartDate,null EndDate); draft(null StartDate); 结束(有效的EndDate). 我在IQueryable上继承了以下语法: iQueryableData .OrderBy(t = t.StartDate == null ? 1 : (t.EndDat
我正在尝试排序一些可以处于以下(推断)状态之一的数据(按此顺序):

> live(有效的StartDate,null EndDate);
> draft(null StartDate);
>结束(有效的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扩展名.这可确保在应用新订单标准时维护先前的订单.对于每个特定情况,返回所需的属性以参与顺序(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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读