Left Join in LINQ

在SQL使用Join可大致分為Inner Join、Outer Join,其中Outer包含Left、Right、Full有的沒的。
今天記錄一下在LINQ(搭配C#)中如何做到Left Join的效果~

假設有2個table"Customer"&"Product"分別記錄顧客與產品資訊,假設這2個table可透過Name、Address欄位串接,最常用的Inner Join寫法如下:
//JOIN 1(Inner):如果customer沒有joinproduct就不保留
var result = customer.Join(product, c => new { c.Name, c.Address }, p => new { p.Name, p.Address }, (c, p) => new { c, p }).ToList();
產出的結果是擁有Product的Customer才會被保留,比如說王小明留下了客戶資料卻沒有訂購任何產品,那麼Join出來的new table是不會有王小明的資訊。

如果要以Customer為基準,無論有無訂購產品皆保留顧客資訊,那麼就要以Customer為Left Table作Left Join,寫法如下:
//JOIN 2(Outer-Left Join):即使customer沒有對應的product,也保留
var result = (from c in customer
join p in product
on new { c.Name, c.Address } equals new { p.Name, p.Address } into newProduct
from newP in newProduct.DefaultIfEmpty()
select new { c, newP }).Distinct();

沒有留言: