将 Sql 查询转换为包含条件 OrderBy / ThenBy 子句的 linq

Convert Sql query to linq contains conditional OrderBy / ThenBy clause

tableA 包含用户最近访问过的项目列表,用户可以选择 pin/remove 列表。

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

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();

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

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

编辑: 此外,如果您不喜欢拆分和连接的想法,您可以尝试这个想法:

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

你可以试试这个:

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

尝试:

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