我是C#的新手。我有一系列列表,看起来像这样:
var baskets = [
[apples, oranges, peaches],
[oranges, grapes, bananas],
[oranges, grapes, apples]
[bananas, strawberries, peaches]
]
我需要把它变成一个单独的数组,每个水果的数量如下:
var fruitCount = [
{fruit: apples , count:2},
{fruit: oranges, count: 3},
{fruit: peaches, count: 2},
{fruit: grapes, count: 2},
{fruit: bananas, count: 2},
{fruit: strawberries, count: 1}]
我在看LINQ's
" .SelectMany
"但它似乎只是将数组压缩成一个列表。老实说,我不知道如何开始。任何人都可以向我指出一个可以提供帮助的代码示例吗?
答案 0 :(得分:4)
试试这个:
var result = baskests.SelectMany(x => x)
.GroupBy(x => x)
.Select(x => new {
Fruit = x.Key,
Count = x.Count()
});
这正是Rahul在评论中所建议的。它首先将所有水果展平为一个包含重复项的列表,而不是将列表分组。最后,Select
- 语句将为具有Fruit
- 和Count
- 属性的每个组创建一个匿名实例。
答案 1 :(得分:1)
您需要使用SelectMany
展平数组,然后对条目进行分组:
var flattened = baskets.SelectMany(basket => basket);
var fruitCount = flattened.GroupBy(fruit => fruit,
(fruit, g) => new { fruit, count = g.Count()});