[英]C# Count Items across an Array of Lists
我是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
”,但它似乎將數組弄平到一個列表中。 老實說,我不知道如何開始。 誰能指出我可以幫助您的代碼示例?
嘗試這個:
var result = baskests.SelectMany(x => x)
.GroupBy(x => x)
.Select(x => new {
Fruit = x.Key,
Count = x.Count()
});
這正是拉胡爾在評論中建議的。 首先將所有水果拼合到一個包含重復項的列表中,然后對該列表進行分組。 最后, Select
語句來將用於具有每個組創建一個匿名實例Fruit
和- Count
-屬性。
您需要使用SelectMany
展平數組,然后對條目進行分組:
var flattened = baskets.SelectMany(basket => basket);
var fruitCount = flattened.GroupBy(fruit => fruit,
(fruit, g) => new { fruit, count = g.Count()});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.