C# 分组,然后展平项目
我有一个具有以下属性的对象列表:C# 分组,然后展平项目,c#,linq,C#,Linq,我有一个具有以下属性的对象列表: int TownId, int CompanyId, int ProductId, int[] Prices int TownId, int CompanyId, int[] Products, int[] Prices 我想把它变成一个TownCompany对象的列表;每个项目具有以下属性: int TownId, int CompanyId, int ProductId, int[] Prices int TownId, int CompanyId,
int TownId, int CompanyId, int ProductId, int[] Prices
int TownId, int CompanyId, int[] Products, int[] Prices
我想把它变成一个TownCompany
对象的列表;每个项目具有以下属性:
int TownId, int CompanyId, int ProductId, int[] Prices
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] }
}
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()
});
您只需要为
价格选择多个;对于ProductId
,它是一个简单的选择:
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()
});
如果我没看错你的话,那么像这样的事情:
{
{ TownId: 1, CompanyId: 10, Products: [100, 101], Prices: [1, 2, 3] }
}
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()
});
不,不完全是这样,我添加了一个例子来澄清。这将为每个产品创建单独的项目,而我希望它们组合在一起。两个回答者之间有一点“协作”,但您的先编译并工作!谢谢。@GrahamClark“Collaboration”这个词完全不适合描述所发生的事情。@Mario因为你在2K以上,你可以自由编辑其他人的答案,你的编辑将立即显示,而无需等待批准。把别人的答案复制成你的答案不是正确的做法,除非修复相当重要(这里肯定不是这样)。简单一点。事实上,当我看到问题的编辑并理解OP的意思时,我就在没有你回答的情况下创建了代码。因为我已经给出了答案,所以我匆忙创建了新的解决方案,直到您给出答案之后,我才注意到。我后来从你那里复制的唯一一件事是.ToArray()
@Mario当然,你复制了。你也为lambdas中的每个变量取了相同的名字,这完全是巧合。不过,说真的,当你犯了错误时,最好承认它,然后继续前进。这让每个人都免了一些烦恼。好吧,至少他改变了换行符。很抱歉给你带来不便,但我确实是自己创造的。很明显,我不能向你证明这一点,与你的相比,我的名声很低,我处于一个不利的地位。如果有帮助的话,请随意比较我的其他答案,尽管我怀疑它会有帮助。只是想帮点忙。所以,如果你愿意,我可以删除我的答案,我真的不在乎=/