Sasha Egania
Sasha Egania

Reputation: 53

C# Count Items across an Array of Lists

I am new to C#. I have an array of lists that looks something like this:

var baskets = [
[apples, oranges, peaches],
[oranges, grapes, bananas],
[oranges, grapes, apples]
[bananas, strawberries, peaches]
]

I need to turn it into a single array with a count of each fruit like this:

   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}]

I was looking at LINQ's ".SelectMany" but it just seems to flatten out the array into one list. I honestly don't know how to begin. Can anyone point me to a code sample that could help?

Upvotes: 0

Views: 197

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Try this:

var result = baskests.SelectMany(x => x)
    .GroupBy(x => x)
    .Select(x => new { 
        Fruit = x.Key, 
        Count = x.Count() 
    });

This does exactly what Rahul suggested in the comment. It first flattens all fruits into one single list containing duplicates and than groups the list. Finally the Select-statement will create an anonymous instance for every group having a Fruit- and a Count-property.

Upvotes: 4

René Vogt
René Vogt

Reputation: 43876

You need to flatten the array with SelectMany and then group the entries:

var flattened = baskets.SelectMany(basket => basket);
var fruitCount = flattened.GroupBy(fruit => fruit, 
                                   (fruit, g) => new { fruit, count = g.Count()});

Upvotes: 1

Related Questions