在查询中按行字段递减排序 [英] Order by descending by row field in query
本文介绍了在查询中按行字段递减排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写一个EF查询,它根据条件按升序或降序进行排序。以下是我的伪代码:
I want to write a EF query which does order by ascending or descending based on condition. Following is the my pseudo code:
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
我该怎么做?
更新
这与 q =条件不同q.OrderBy(..):q.OrderByDescending(..)
在引用的重复问题中标记,排序顺序根据行内的值而不是查询外部的标志而不同。
This is not same as q = condition ? q.OrderBy(..) : q.OrderByDescending(..)
as marked in referenced duplicate question, sorting order differs based on value within the row instead of a flag outside query.
推荐答案
您可以在OrderBy中提供复杂的表达式...
You can supply complex expressions in 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生成将
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]
这篇关于在查询中按行字段递减排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文