c# - LINQ: Join conditionally to two different tables depending on each item -


is there way set if in linq statement?

return(from x in db.products x.id == id      if(x.type == 1){         join y in db.category1 on x.iditem equals y.id     }else if(x.type == 2){         join z in db.category2 on x.iditem equals z.id     } select new {....}).tolist(); 

i know code wrong question is:

what's best way implement this?

note, following not solve problem op having because join predicate depends on each item. following helps if condition known entire query @ once:


you split query:

var part1 = x in db.products x.id == id select x; var part2 =  b ? (from x in part1 join db.category1 select { x, joineditem }) :  (from x in part1 join db.category2 select { x, joineditem }); 

quickly written up. need make anonymous types on both queries compatible. that's important thing.


Comments