通过静态列和分组列进行分组 [英] Group by with static columns and grouped columns

查看:125
本文介绍了通过静态列和分组列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm use to sql, and not quite used to linq yet. May I ask how do I group columns based on a value, and group other columns to a list and make the other columns static?

例如

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

My linq query to make Table 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
}

推荐答案

假设您需要同时按人员"和街道地址.

Assuming you need to group by both People & 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
                            });

这里,数据是要分组的数据源.

Here, data is the data source you want to group.

这篇关于通过静态列和分组列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆