If Else in LINQ

后端 未结 6 1579
谎友^
谎友^ 2020-12-01 04:38

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


        
6条回答
  •  悲哀的现实
    2020-12-01 05:08

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

提交回复
热议问题