2011-03-02 81 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