2016-05-17 95 views
0

我在StackOverflow.com上阅读其他文章和评论,但无法理解解决方案。Linq Dynamic OrderBy

下面是代码:

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

注:

radDropDownList1有两个项目。 0意味着orderby必须基于消息的SendDate,1意味着orderby必须基于SendDate,DoneDate和注释中的最大日期之间的最大值。上面的代码不会返回我期望的结果。请帮帮我。

回答

1

按照我的第一次看,启动e变量的代码被错误地编写。

使用条件?:运营商应该看起来像一个适当的if ... then ... elseif声明:

var answer = condition ? first_expression : second_expression 

参见:

if (radDropDownList1.SelectedIndex == 0) 
    a 
else if (a >= b) 
    if (a >= d) 
    a 
    else 
    d 
else if (b >= d) 
    b 
else 
    d 

注:?: Operator (C# Reference)

让我们使用标准的符号将它分成多个行i不要使用{}括号来使代码更易读。

如果您使用多个if... then ... elseif语句,您必须特别小心!

0

上面的代码不返回结果,我期待:你的条件表达式是原因

我建议你这样写:

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

编辑:
是的,抱歉,正如你所提到的,SQL不会知道DateTime Ticks

让我们找到最大的是这样的:

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

附:优雅将取决于你;)

+0

我做了你说的,但得到的错误说:成员'System.DateTime.Ticks'没有支持转换到SQL。 – Mohsen

+0

我已经通过添加详细信息编辑了答案 – meorfi

+0

我刚才观察到,您应该在表达式中使用'd'而不是'c' let tempMax2 = tempMax1> c? tempMax1:c'。所以它会是'let tempMax2 = tempMax1> d? tempMax1:d' – meorfi