10

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

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

我想把它变成一个TownCompany对象列表;每个项目具有以下属性:

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

所以我可以

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

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

如何将此组列表转换为每个键的扁平列表列表?我希望我说得通。

例子:

如果我的原始清单是这样的:

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

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

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

2 回答 2

16

SelectMany只需要Prices; 因为ProductId它很简单Select

flatList
.GroupBy(l => new { l.TownId, l.CompanyId })
.Select(g => new {
    g.Key.TownId
,   g.Key.CompanyId
,   ProductIds = g.Select(o => o.ProductId).ToArray()
,   Prices = g.SelectMany(o => o.Prices).ToArray()
});
于 2012-11-09T11:55:19.537 回答
15

如果我理解正确,那么是这样的:

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()
        });
于 2012-11-09T11:56:29.643 回答