LINQ查询中的嵌套条件运算符

时间:2016-10-18 21:48:13

标签: c# linq

使用VS 2013(尚未推出C#6.0)

我有以下可用的LINQ:

var radData = (from stop in dbContext.stop_details
               join del in dbContext.stop_event on stop.id equals del.stop_id into Inners
               from sd in Inners.DefaultIfEmpty()
               where stop.ship_date == startDate && stop.cust_ref_5_terminalID == "HEND"
               select new
               {
                   shipDate = stop.ship_date,
                   custRef = stop.cust_ref_5_terminalID,
                   name = stop.customer.customer_name,
                   ontime = (int?)sd.ontime_performance,
                   OTP = ((int?)sd.ontime_performance) < 1 ? "Ontime" : "Late"
               }).ToList();

OTP的值必须如下,具体取决于ontime_performance

  • Null - &#34; open&#34;
  • &lt; 1&#34; Ontime&#34;
  • 1&#34;延迟一天&#34;
  • 2&#34;延迟两天&#34;
  • &#39;&gt; 2&#34;迟到三天或更多天&#34;

有没有办法筑巢呢?到目前为止我没有尝试过任何工作..

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以按如下方式链接多个?:

var radData = (from stop in dbContext.stop_details
               join del in dbContext.stop_event on stop.id equals del.stop_id into Inners
               from sd in Inners.DefaultIfEmpty()
               where stop.ship_date == startDate && 
                     stop.cust_ref_5_terminalID == "HEND"

               let value = ((int?)sd.ontime_performance)
               select new
               {
                   shipDate = stop.ship_date,
                   custRef = stop.cust_ref_5_terminalID,
                   name = stop.customer.customer_name,
                   ontime = (int?)sd.ontime_performance,
                   OTP = value == null ? "Open" :
                         value < 1 ? "On time" :
                         value == 1 ? "One Day Late" : 
                         value == 2 ? "Two Days Late" : "Three or more days late"
               }).ToList();

此外,您可以将字段存储在变量中,因此您不需要每次都将其强制转换:let value = ((int?)sd.ontime_performance)

BTW - 字段为int?您可以将value < 1更改为value == 0

与其他条件一致,不那么令人困惑