[c#]与静态列和分组的列分组

标签: Linq C#
发布时间: 2017/2/28 21:22:24
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我是使用 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
}

解决方法 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
                            });

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

官方微信
官方QQ群
31647020