开发者

linq join with case condition

Hi may i know how to do a select "case" condition in using linq? The commented out code are my question. how do i put the condition there? my code:

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开发者_JS百科 equals c.Id
    where u.Id == 5
    select new{ u, p, soi, either i or c};


You have to use some outer join trick to accomplish this, one straightforward method is via DefaultIfEmpty(). Essentially you create an inner join then expand it with missing rows:

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};

Be careful about this last statement ic = oi ?? oc, since the types differ the anonymous type will use System.Object declaration so it can accommodate both types, if you want to use strong typed support maybe a better option would be to return both oc and ic and then test. You should best decide that based on how you use this query late ron.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜