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 }
var query = someList. Where(a => a == "something"); if (condition) { query = query. Where(b => b == "something else"); } var result = query. ToList();
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.
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.
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) }
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With