2011-03-02 106 views
0

我有一個LINQ匿名集合稱爲ProgramRevisions:的LINQ to SQL - 獲取所有記錄從兩個集合

 
RevisionID  RevisionName 
1    Government 
2    Business 
3    Public Sector 

我也有一個匿名的集合稱爲支出

 
ExpDisplay  ExpSort  ExpProgramRevID 
N/A   0001   1 
Water/Sewer 0002   1 
Trash/Bulk  0004   1 
Debt Service 0003   2 
Loan Collect 0005   2 

我需要得到這樣的結果設置:

 
ExpDisplay ExpSort  ExpProgramRevID  ProgramRevName 
N/A   0001   1     Government 
Water/Sewer 0002   1     Government 
Trash/Bulk  0004   1     Government 
Debt Service 0003   2     Business 
Loan Collect 0005   2     Business 
NULL   NULL   3     Public Sector 

換句話說,我需要匹配ProgramRevID上的所有行,並且我需要一個entr對於每個ProgramRevision,是否它在支出中具有匹配的行。

我似乎無法得到我需要做的這個查詢的頭。有什麼建議麼?

回答

3

這將返回你所期望的準確結果(修訂LEFT JOIN支出):

var revisions = new List<Revision>(); 
revisions.Add(new Revision { Id = 1, Name = "Government" }); 
revisions.Add(new Revision { Id = 2, Name = "Business" }); 
revisions.Add(new Revision { Id = 3, Name = "Public Sector" }); 

var expenditures = new List<Expenditure>(); 
expenditures.Add(new Expenditure { Display = "N/A", ExpSort = "0001", RevisionId = 1 }); 
expenditures.Add(new Expenditure { Display = "Water/Sewer", ExpSort = "0002", RevisionId = 1 }); 
expenditures.Add(new Expenditure { Display = "Trash/Bulk", ExpSort = "0003", RevisionId = 1 }); 
expenditures.Add(new Expenditure { Display = "Debt Service", ExpSort = "0004", RevisionId = 2 }); 
expenditures.Add(new Expenditure { Display = "Loan Collect", ExpSort = "0005", RevisionId = 2 }); 

var result = revisions 
    .GroupJoin(expenditures, 
     r => r.Id, 
     e => e.RevisionId, 
     (r, e) => new { Revision = r, Expenditures = e.DefaultIfEmpty() } 
    ).SelectMany(x => 
      x.Expenditures.Select(e => new { Revision = x.Revision, Expenditure = e }) 
    ).Select(x => new 
    { 
     Display = (x.Expenditure == null ? null : x.Expenditure.Display), 
     ExpSort = (x.Expenditure == null ? null : x.Expenditure.ExpSort), 
     RevisionId = x.Revision.Id, 
     RevisionName = x.Revision.Name 
    }); 
+0

這做到了!謝謝! – 2011-03-02 16:32:55