[LINQ]如何做left join

  • 1711
  • 0
  • 2019-10-18

[LINQ]如何做left join

void Main()
{
	using (MyEntities db = new MyEntities())
	{
	    var querys = 					
			from m in db.Member.AsEnumerable() //AsEnumerable讓此linq查詢裡面可以使用一般function
			
			//left join log資料表,因為可能join不到,所以此join結果可能為null
			join log in db.Member_Log on m.MemberSN equals log.MemberSN			
			//因此我把join結果取名稱為maybenull(其實可以隨便取)
			//最後再設定maybenull可能為空即可(maybenull.DefaultIfEmpty())
			into maybenull				
			from log in maybenull.DefaultIfEmpty()
			
			select new { MyCol1 = m.MemberSN, MyCol2 = GetResultString(log) };
		foreach (var query in querys)
		{
			Console.WriteLine("MyCol1=" + query.MyCol1 + ", MyCol2=" + query.MyCol2);
			Console.WriteLine();
		}
	}
}


利用LinqPad執行結果:



參考資料:
在LINQ中實踐多條件LEFT JOIN
https://blog.darkthread.net/blog/linq-left-join/
分享幾個 LINQ to SQL 執行各種 Join 查詢的技巧
https://blog.miniasp.com/post/2010/10/14/LINQ-to-SQL-Query-Tips-INNER-JOIN-and-LEFT-JOIN