2011-02-10 79 views
5

嗨,我可以知道如何做一個選擇「案件」使用LINQ條件? 註釋掉的代碼是我的問題。我如何把病情放在那裏? 我的代碼:LINQ加入案件條件

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

回答

2

您必須使用一些外連接把戲做到這一點,一個簡單的方法是通過DefaultIfEmpty()。基本上你創建一個內部聯接,然後用缺少的行展開:,

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然後測試。你應該根據你遲來使用這個查詢來做出最好的決定。

+0

@mmix嗨我得到了這個錯誤「連接子句中的一個表達式的類型不正確,在'GroupJoin'的調用中類型推斷失敗。在行中加入我在庫存上的新{a ... – VeecoTech 2011-02-10 10:31:55