分组,然后展平项目 [英] Group by and then flatten the items

查看:41
本文介绍了分组,然后展平项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下属性的对象列表:

I've got a list of objects with the following properties:

int TownId, int CompanyId, int ProductId, int[] Prices

我想将其转换为 TownCompany 对象的列表;每个项目都具有以下属性:

I want to turn this into a list of TownCompany objects; each item having the following properties:

int TownId, int CompanyId, int[] Products, int[] Prices

所以我可以做

flatList.GroupBy(l => new { l.TownId, l.CompanyId })

获取组列表,其中包含每个镇/公司对的所有产品和价格.现在,对于此查找中的每个键,我想展平/合并所有值.似乎我应该能够使用 SelectMany ,但是我总是对要提供的投影感到困惑...

To get a list of groups, which has all the products and prices for each town/company pair. Now, for each key in this lookup, I want to flatten/merge all the values. Seems like I should be able to use SelectMany, but I always get a bit confused by what projections to supply to it...

如何将这个组列表变成每个键的拼合列表列表?我希望我有道理.

How do I turn this list of groups into a list of flattened lists for each key? I hope I've made sense.

示例:

如果我的原始列表是这样的:

If my original list is this:

new[] {
    new Item { TownId = 1, CompanyId = 10, ProductId = 100, Prices = new [] { 1, 2 } },
    new Item { TownId = 1, CompanyId = 10, ProductId = 101, Prices = new [] { 3 } },
};

我想要一个看起来像这样的列表:

I want a list that looks like this:

{
    { TownId: 1, CompanyId: 10, Products: [100, 101], Prices: [1, 2, 3] }
}

推荐答案

如果我对您的理解正确,则类似以下内容:

If I understood you correctly, then something like this:

flatList.GroupBy(l => new { l.TownId, l.CompanyId })
        .Select(g => new 
        {
            TownId = g.Key.TownId,
            CompanyId = g.Key.CompanyId,   
            Products = g.Select(o => o.ProductId).ToArray(),
            Prices = g.SelectMany(o => o.Prices).ToArray()
        });

这篇关于分组,然后展平项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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