分组依据使用静态列和分组列

本文关键字:静态 | 更新日期: 2023-09-27 18:34:03

我已经习惯了sql,但还不太习惯linq。请问如何根据值对列进行分组,并将其他列分组到列表中并使其他列成为静态列?

例如

People   |  Businesses   | StreetAddress
 John    |    Store 1    |  Hello Blvd.
 John    |    Store 2    |  Hello Blvd.

生产

People   |       Businesses                 | StreetAddress
 John    |    ["Store 1", "Store 2"]        |  Hello Blvd.

我的 linq 查询使表 1

from x in ctx.People
join ownership in ctx.Ownerships
    on x.Id equals ownership.Owner_Id into ps
from ownership in ps.DefaultIfEmpty()
join Business in ctx.Businesses
    on ownership.Business_Id equals  Business.Id into ps2
from Business in ps2.DefaultIfEmpty()
select new PersonDTO
{
    Id            = x.Id,
    Business      = Business.Name,
    StreetAddress = x.Addresses.FirstOrDefault().Line1
}

分组依据使用静态列和分组列

假设您需要按人员和街道地址分组。

 var result = data.GroupBy(x => new { x.People, x.StreetAddress })
                  .ToList()
                  .Select(x => new 
                            {
                                People = x.Key.People,
                                Business = String.Join(",",x.Select(z => z.Business),
                                StreetAddress x.Key.StreetAddress
                            });

编辑:在列表中获取Business

 var result = data.GroupBy(x => new { x.People, x.StreetAddress })
                  .Select(x => new 
                            {
                                People = x.Key.People,
                                Business = x.Select(z => z.Business).ToList(),
                                StreetAddress x.Key.StreetAddress
                            });

在这里,数据是要分组的数据源。