2016-10-18 48 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 - 歡迎您:) –