【问题标题】:Convert Sql query to linq contains conditional OrderBy / ThenBy clause将 Sql 查询转换为 linq 包含条件 OrderBy / ThenBy 子句
【发布时间】:2023-03-21 08:38:01
【问题描述】:

tableA 包含用户最近访问过的项目列表,用户可以选择固定/删除列表。

我正在尝试的是列表必须按以下查询排序。

select * from tableA
order by ispinned desc,
    case when ispinned = 1 then date end ASC,
    case when ispinned = 0 then date end DESC

但在 LINQ 中它失败了。我尝试过的如下所示。

_lst = _lst.OrderByDescending( x => x.IsPinned).ThenByDescending(x=>x.AccessDate).ToList();

.

_lst = (from data in _lst
        orderby data.IsPinned, data.IsPinned ? data.Date : data.Date descending
        select data ).ToList();

【问题讨论】:

  • 试试:_lst = _lst.OrderByDescending(x => x.IsPinned).ThenBy(x=> x.IsPinned ? x.AccessDate : x.AccessDate.Ticks * -1 ).ToList();
  • 我试过了,它显示编译时错误,因为 ternay 运算符后的数据类型不同Error 17 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'long'
  • @ Khanh 我认为可以进行一些修改,所以您能否发表您的评论作为答案,以便我接受并帮助其他人。
  • 我发布了一个稍作修改的答案

标签: c# linq linq-to-sql


【解决方案1】:

试试:

 _lst = _lst.OrderByDescending(x => x.IsPinned)
            .ThenBy(x=> x.IsPinned ? x.AccessDate.Ticks : x.AccessDate.Ticks * -1 )
            .ToList();

【讨论】:

    【解决方案2】:

    这可能对您有所帮助,但它可能不是最有效的方法。

    var result = _lst.Where(x => x.IsPinned)
                     .OrderBy(x=> x.AccessDate)
                     .Concat(_lst.Where(x => !x.IsPinned)
                                 .OrderByDescending(x=> x.AccessDate))
                     .ToList();
    

    编辑:另外,如果你不喜欢 split&concat 的想法,你可以试试这个想法:

    var result = _lst.OrderByDescending(i=>i.IsPinned).
                    .ThenBy(i=>i.IsPinned? i.Date - DateTime.MinValue :
                                           DateTime.MaxValue - i.Date)
                    .ToList();
    

    【讨论】:

      【解决方案3】:

      你可以试试这个:

      _lst = _lst.OrderByDescending(x => x.IsPinned).ThenBy(x => x.IsPinned ? 
      x.AccessDate : DateTime.MinValue).ThenByDescending(x => !x.IsPinned ?
      x.AccessDate : DateTime.MaxValue).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2020-06-10
        相关资源
        最近更新 更多