tags:

views:

2157

answers:

2
+5  Q: 

If Else in LINQ

Is it possible to use If Else conditional in a LINQ query?

Something like

from p in db.products
if p.price>0
select new
{
  Owner=from q in db.Users
        select q.Name
}
else
select new
{
   Owner = from r in db.ExternalUsers
            select r.Name
}
+2  A: 

I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);

Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).

For a trivial example of the type of thing you can do:

select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };

You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...

Marc Gravell
+7  A: 

This might work...

from p in db.products
    select new
    {
        Owner = (p.price > 0 ?
            from q in db.Users select q.Name :
            from r in db.ExternalUsers select r.Name)
    }
Richard Ev
It'll be interesting to see if that works... if it does, I'd love to see the TSQL (assuming it does eager loading; for lazy loading, probably not too terrible).
Marc Gravell
This should work. The "? :" is translated to a "case" expression and there are subqueries.
David B
Should isn't does. It be nice to have confirmation that this does work. Very useful if it does.
Sam Meldrum
Yes, it does work.I've tested it
Ngu Soon Hui