當前有兩個表,sgroup與sgroupuser,二者經過gKey關聯,而sgroup表記錄的是組,而sgroupuser記錄是組中的用戶,所以在sgroupuser中不必定有數據。須要使用Left Join獲取數據:spa
Linq語法以下:code
var sg = (from g in dc.sgroup
join gu in dc.sgroupuser on g.gKey equals gu.gKey into l
from lgu in l.DefaultIfEmpty()
select new { g, lgu }).ToList();對象
Lambda表達式以下:blog
var sg = dc.sgroup.GroupJoin(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;ci
注意:string
Linq 與Lambda表達式取出的結果有所不一樣.Linq取出的結果的記錄數與Sql中的Left Join的結果相同,而Lambda表達式取出的記錄數是sgroup表中的記錄數,sgroupuser對應的記錄是以對象集合存在於結果中it
附:class
下面是Inner Join:List
Linq語法以下:select
var sg = (from g in dc.sgroup
join gu in dc.sgroupuser on g.gKey equals gu.gKey
select new { g, gu }).ToList();
Lambda表達式以下:
var sg = dc.sgroup.Join(dc.sgroupuser, g => g.gKey, gu => gu.gKey, (g, gu) => new { g, gu }).Select(o=>o).ToList() ;
注意:
上面最後都用到了ToList()方法 , 用ToList()是爲了一次性將數據取到本地.
private string GetSecSolicitImplementCount(DataSet aTmpDs1, DataSet aTmpDs2, int aMonth) { DataTable dt1 = aTmpDs1.Tables[0]; DataTable dt2 = aTmpDs2.Tables[0]; //使用LINQ計算二次招攬任務實施數 var query = from row1 in dt1.AsEnumerable() join row2 in dt2.AsEnumerable() on row1.Field<string>("TASKID") equals row2.Field<string>("TASKID") into l from lgu in l.DefaultIfEmpty() where row1.Field<DateTime>("NEXTSTEPTIME1").Month == aMonth && (lgu == null || row1.Field<DateTime>("NEXTSTEPTIME1") <= lgu.Field<DateTime>("DELIVEREDDATE") ) select new { TaskID = row1.Field<string>("TASKID"), lgu }; var secSolicitImplementCount = query.ToArray().Count(); return secSolicitImplementCount.ToString(); }