Linq connects to case condition

Hi, can I know how to select the case condition when using linq? Commented out code is my question. How can I make a condition? my code is:

var r = from u in Users
    join p in Payments on u.Id equals p.UserId
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id
           //if soi.InventoryTypeId == 1
              //then join i in Inventories on soi.InventoryOrCourseId equals i.Id
           //elseif soi.InventorytypeId ==2
              //then join c in Courses on soi.InventoryOrCourseId equals c.Id
    where u.Id == 5
    select new{ u, p, soi, either i or c};
+5
source share
1 answer

To accomplish this, you need to use some kind of external trick, one simple method is through DefaultIfEmpty(). Essentially, you create an inner join and then expand it with the missing lines:

var r = from u in Users
    join p in Payments on u.Id equals p.UserId
    join soi in SaleOrderItems on p.ReferenceId equals soi.Id
    join i in Inventories on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 1, b = i.Id} into g1
    from oi in g1.DefaultIfEmpty()
    join c in Courses on new {a = soi.InventoryTypeId, b = soi.InventoryOrCourseId } equals new {a = 2, b = c.Id} into g2
    from oc in g2.DefaultIfEmpty()
    where u.Id == 5
    select new{ u, p, soi, ic = oi ?? oc};

ic = oi ?? oc, , System.Object, , , , oc ic, . , , ron.

+2

All Articles