Joe Ruder
Joe Ruder

Reputation: 2194

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:

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

Thank you.

Upvotes: 2

Views: 1425

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

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

Upvotes: 1

Related Questions