我有一个具有以下属性的对象列表:
int TownId, int CompanyId, int ProductId, int[] Prices
Run Code Online (Sandbox Code Playgroud)
我想把它变成一个TownCompany对象列表; 每个项目具有以下属性:
int TownId, int CompanyId, int[] Products, int[] Prices
Run Code Online (Sandbox Code Playgroud)
所以我能做到
flatList.GroupBy(l => new { l.TownId, l.CompanyId })
Run Code Online (Sandbox Code Playgroud)
获取组列表,其中包含每个城镇/公司对的所有产品和价格.现在,对于此查找中的每个键,我想要展平/合并所有值.好像我应该可以使用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 } },
};
Run Code Online (Sandbox Code Playgroud)
我想要一个如下所示的列表:
{
{ TownId: 1, CompanyId: 10, Products: [100, 101], Prices: [1, 2, 3] }
}
Run Code Online (Sandbox Code Playgroud)
das*_*ght 15
你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()
});
Run Code Online (Sandbox Code Playgroud)
Mar*_*num 13
如果我理解正确,那么这样的事情:
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()
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8054 次 |
| 最近记录: |