[英]Linq Dynamic OrderBy
I read other post and comments in StackOverflow.com but couldn't understand the solution. 我在StackOverflow.com上阅读了其他帖子和评论,但无法理解解决方案。
Here is the code: 这是代码:
var qry = (from m in db.Messages
join r in db.Recievers on m.Id equals r.Message_Id
let a = m.SendDate
let b = (m.DoneDate != null ? m.DoneDate : DateTime.MinValue)
let c = m.Comments.Max(c => c.CommentDate)
let d = (c != null ? c : DateTime.MinValue)
let e = (radDropDownList1.SelectedIndex == 0 ? a : a >= b ? a >= d ? a : d : b >= d ? b : d)
orderby e descending
select m).Distinct();
Notes: 笔记:
radDropDownList1 has two items. radDropDownList1有两个项目。 the 0 means the orderby must be based on SendDate of messages and 1 means the orderby must be based on the biggest value among SendDate, DoneDate and maximum date in comments.
0表示orderby必须基于消息的SendDate,1表示orderby必须基于SendDate,DoneDate和注释中的最大日期中的最大值。 The above code does not return the result I expect.
上面的代码未返回我期望的结果。 Please help me.
请帮我。
As per my first look, the code to initiate e
variable is wrongly written. 乍看之下,初始化
e
变量的代码写错了。
A proper if ... then ... elseif
statement using conditional ?:
operator should look like: 使用条件
?:
运算符的适当的if ... then ... elseif
语句应类似于:
var answer = condition ? first_expression : second_expression
See: ?: Operator (C# Reference) 参见: ?:运算符(C#参考)
Let split it into multiple lines using standard notation: 让我们使用标准符号将其分成多行:
if (radDropDownList1.SelectedIndex == 0)
a
else if (a >= b)
if (a >= d)
a
else
d
else if (b >= d)
b
else
d
Note: i do not use {}
brackets to leave code more readible. 注意:我不使用
{}
括号使代码更易读。
In case when you use multiple if... then ... elseif
statements, you have to excercise special caution! 如果您使用多个
if... then ... elseif
语句,则必须特别注意!
The above code does not return the result I expect: you conditional expression is the cause 上面的代码未返回我期望的结果:条件表达式是原因
I would suggest you to write in this way: 我建议你这样写:
let e = radDropDownList1.SelectedIndex == 0 ? a /*order by SendDate*/
/*otherwise , order by MAX(a, b, c)*/
: new DateTime(Math.Max(a.Ticks, Math.Max(b.Ticks, c.Ticks)))
EDIT: 编辑:
Yes, sorry, as you mentioned, the SQL will not know about DateTime Ticks 是的,很抱歉,正如您提到的,SQL不会知道有关DateTime滴答的信息
Let's find the max in this way: 让我们以这种方式找到最大值:
var selectedIndex = radDropDownList1.SelectedIndex;
var query =
(from m in db.Messages
join r in db.Recievers
on m.Id equals r.Message_Id
let a = m.SendDate
let b = (m.DoneDate != null ? m.DoneDate : DateTime.MinValue)
let c = m.Comments.Max(c => c.CommentDate)
let d = (c != null ? c : DateTime.MinValue)
let tempMax1 = a > b ? a : b
let tempMax2 = tempMax1 > c ? tempMax1 : c
let e = (
selectedIndex == 0 ? a /*order by SendDate*/
: tempMax2) /*otherwise , order by MAX(a, b, c)*/
orderby e descending
select m)
.Distinct();
PS The elegance will be up to you ;) PS优雅将取决于您;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.