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
}
If clientId = 0 we want ALL employees,. but for any clientId between 1 and 999 we want only clients with that ID. I was having issues with seperate LINQ statements not being the same (Deleted/Clients filters need to be on all queries), so by add these two lines it works (all be it until we have 999+ clients - which would be a happy re-factor day!!
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:
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...
my example:
Answer above is not suitable for complicate Linq expression. All you need is:
This might work...
you should change like this: