我用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
}
答案 0 :(得分:1)
假设您需要按人员和组合分组的StreetAddress。
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
});
此处,数据是您要分组的数据源。