Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 927
Graviton Avatar asked Jan 14 '09 14:01

Graviton


People also ask

How write if in Linq?

var query = someList. Where(a => a == "something"); if (condition) { query = query. Where(b => b == "something else"); } var result = query. ToList();

What is Linq in C# with example?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.

Which clause is used for conditions in Linq?

In LINQ, we can use Where() clause in the query to define multiple conditions, as shown below. This is how we can use LINQ where clause filtering operator to filter data based on conditions.


2 Answers

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)     } 
like image 175
Richard Ev Avatar answered Sep 24 '22 08:09

Richard Ev


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...

like image 30
Marc Gravell Avatar answered Sep 22 '22 08:09

Marc Gravell