在查询中按行字段降序排序

时间:2017-07-31 08:33:47

标签: c# entity-framework linq

我想编写一个EF查询,它根据条件按升序或降序排序。以下是我的伪代码:

false

我该怎么做?

更新

这与引用的重复问题中标记的 var result= q.OrderByDescending(x => x.StatusId == 3) if( x.StatusId == 3) then order by x.ReserveDate if( x.StatusId != 3 ) then order by descending x.LastUpdateDate 不同,排序顺序根据行内的值而不是查询外的标志而不同。

2 个答案:

答案 0 :(得分:1)

您可以在OrderBy ...

中提供复杂的表达式
// you might have to give bounding start,end for
// for this query to work correctly...

var end = DateTime.Now;
var start = end.AddYears(-100);

var result = q.OrderBy( 
               x => x.StatusId == 3 ?  

               // this will sort by in ascending order 
               DbFunctions.DiffDays(x.ReserveDate, start) :

               // this will sort in descending order
               DbFunctions.DiffDays(end, x.LastUpdateDate) );

SQL Generated将是

SELECT 
    ...
    ...
    FROM ( SELECT CASE 
        WHEN ([Extent2].[StatusId ] = 3) 
            THEN DATEDIFF (day, @p__linq__0, [Extent1].[ReserveDate]) 
        ELSE 
            DATEDIFF (day, [Extent1].[LastUpdateDate], @p__linq__1) 
        END AS [C1] 
        FROM  [dbo].[Table] AS [Extent1]
    )  AS [Project1]
    ORDER BY [Project1].[C1]

答案 1 :(得分:0)

正如BoessB's评论所说,这对于两个连接的查询来说最简单:

var q1 = from x in source
         where x.StatusId == 3
         order by x.ReserveDate;
var q2 = from x in source
         where x.StatusId != 3
         order by x.LastUpdateDate descending;

var results  = await q1.Concat(q2).ToListAsync();

如果您可以从letReserveDate创建一个以正确方式排序的派生字段(LastUpdateDate子句帮助),则可以在单个表达式中执行此操作。但我建议拆分查询会更清楚。

相关问题