MostlyLucid MostlyLucid - 1 month ago 8
C# Question

Nested conditional operator in a LINQ query

Using VS 2013 (not C# 6.0 yet)

I have the following LINQ which works:

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


But the value of
OTP
needs to be the following depending on
ontime_performance
:


  • Null - "open"

  • <1 "Ontime"

  • 1 "One Day Late"

  • 2 "Two Days Late"

  • '>2 "Three or more days late"



Is there a way to nest this? Nothing I have tried so far works..

Thank you.

Answer

You can chain many ?: as follows:

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

Also you can store the field in a variable so you don't need to cast it each time: let value = ((int?)sd.ontime_performance)

BTW - the field being int? you can change the value < 1 to value == 0. Consistent with the other conditions and less confusing