2018年10月16日 星期二

[LINQ] LEFT JOIN / GROUP JOIN

GroupJoin 可以得到與Left Join相似的結果,接下來只要使用 Select過濾GroupJoin 中的內容就可以得到想要的結果。
(使用DefaultIfEmpty 因匿名型別無法輸出NULL(無法轉換成強型別),需特別注意Null的處理)


例:

Dim Query = _

            From oe In dt1.AsEnumerable _

            Group Join i In dt2.AsEnumerable _

            On oe.Field(Of String)("employeeid") Equals i.Field(Of String)("employeeid") Into Group _

            From p In Group.DefaultIfEmpty() _


            Select 部門 = oe.Field(Of Int32)("Dep"), _

                   員工 = oe.Field(Of String)("employeeid"), _

                   早餐 = If(p Is Nothing, "", p.Field(Of String)("早餐")), _

                   午餐 = If(p Is Nothing, "", p.Field(Of String)("午餐")), _

                   晚餐 = If(p Is Nothing, "", p.Field(Of String)("晚餐"))


//array1 LEFT JOIN array2
var q = array1
            .Join(array2,
                     a1 => ID,
                     a2 => a2.id,
                     (a1, a2) => new{
                                         A= a1.ID,
                                         B= a1.employee_id,
                                         a2
                                       })
            .Where(x => x.Date < DateTime.Now)
            .Select(x => x);




當要撈出LEFT JOIN的值為空值的部分,可以加入 Where IsNothing(p) ,就可以撈出想要的資料。


例:

Dim qMaster = (From m In dtM.AsEnumerable _

                           Group Join l In dtL.AsEnumerable _

                           On m.Item("id") Equals l.Item("ID") Into Group _

                           From p In Group.DefaultIfEmpty() _

                           Where IsNothing(p) _

                           Select m).CopyToDataTable


沒有留言:

張貼留言