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

C# 将Sql查询转换为linq包含条件OrderBy/ThenBy子句,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,表格A包含用户最近访问的项目列表,用户可以选择锁定/删除该列表 我尝试的是列表必须按以下查询排序 select * from tableA order by ispinned desc, case when ispinned = 1 then date end ASC, case when ispinned = 0 then date end DESC 但在林克,它失败了。我试过的是如下所示 _lst = _lst.OrderByDescending( x => x.Is

表格A
包含用户最近访问的项目列表,用户可以选择锁定/删除该列表

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

select * from tableA
order by ispinned desc,
    case when ispinned = 1 then date end ASC,
    case when ispinned = 0 then date end DESC
但在林克,它失败了。我试过的是如下所示

_lst = _lst.OrderByDescending( x => x.IsPinned).ThenByDescending(x=>x.AccessDate).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();
尝试:


try:
_lst=_lst.OrderByDescending(x=>x.IsPinned)。然后by(x=>x.IsPinned?x.AccessDate:x.AccessDate.Ticks*-1)。ToList()我尝试了这个,它显示了编译时错误,因为ternay运算符后的数据类型不同
错误17无法确定条件表达式的类型,因为'System.DateTime'和'long'之间没有隐式转换。
@Khanh我想可以做一些修改,所以请将您的注释作为答案发布,这样我就可以接受它,并帮助别人。我贴了一个答案,稍加修改
_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();