2016-10-18 47 views
1

使用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

  • 空 - “打开”
  • < 1 “龙泰”
  • 1 “晚一天”
  • 2 “两天迟到”
  • “> 2 “的三个或更多日晚”

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

谢谢。

回答

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 - 现场您可以将value < 1更改为value == 0。与其他条件相一致,不易混淆

+0

完美 - 感谢额外的价值部分。 <1需要保留,因为还有负值返回。很好的答案。 –

+0

@MostlyLucid - 欢迎您:) –