LINQ to SQL - 从两个集合中获取所有记录

时间:2011-03-02 15:56:12

标签: linq-to-sql

我有一个名为ProgramRevisions的LINQ匿名集合:

RevisionID     RevisionName
1              Government
2              Business
3              Public Sector

我还有一个名为Expenditures的匿名集合

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上匹配的所有行,并且我需要为每个ProgramRevision创建一个条目,无论它是否在支出中都有匹配的行。

我似乎无法理解我需要这样做的查询。有什么建议吗?

1 个答案:

答案 0 :(得分: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
    });