LINQ-连接3个表并选择带有两个列表的项目

时间:2019-05-11 22:39:24

标签: entity-framework linq join group-by

我有一个Company表,该表链接到Address和Contact表。一个公司可以有多个地址和联系人。

我正在与LINQ一起加入他们的行列,并使用GroupBy按公司分组,但是我不确定如何从中获取地址和联系人列表。我所看到的唯一示例只是试图获取一个Key列表。

我该如何编写“选择”以获取具有地址列表和联系人列表的单个公司?

以下是我到目前为止的内容:

var companiesList = 
    (from company in _context.Company
        join address in _context.Address
        on company.CompanyId equals address.CompanyId
        join contact in _context.Contact
        on company.CompanyId equals contact.CompanyId
        select new { company, address, contact })
    .GroupBy(x => x.company)
    .Select(group => new {
        Company = group.Key,
        Addresses = ??,
        Contacts = ??
    })
    .AsEnumerable();

1 个答案:

答案 0 :(得分:0)

您非常接近答案。您可以使用

group.ToList().Select(c=>c.address),

group.ToList().Select(c=>c.contact)

完整示例

var companiesList  =  (from company in _context.Company
        join address in _context.Address
        on company.CompanyId equals address.CompanyId
        join contact in _context.Contact
        on company.CompanyId equals contact.CompanyId
        select new { company, address, contact })
    .GroupBy(x => x.company)
    .Select(group => new {
        Company = group.Key,
        Addresses = group.ToList().Select(c=>c.address),
        Contacts = group.ToList().Select(c=>c.contact)
    })