Reputation: 13
I've faced the following problem using LINQ. Say I have a collection of numbers in range from one to five: [1,2,4,5,0,3,1 ...]
. There could be any number of those in that array. What I want is to transform that array into following structure: [{number:0, count:5},{number:1, count:3}, {number:2, count:0}....]
. If I use GroupBy
I miss entry for number 2. Is there any elegant and effective way of doing this using LINQ?
Upvotes: 0
Views: 121
Reputation: 1529
List<KeyValuePair<string, int>> pairs = new List<KeyValuePair<string,int>>();
for(int i = 0; i < 5; i++)
{
pairs.Add(new KeyValuePair<string, int>("number:" + i, arrayOfNums.Select(x => x == i).Count()));
}
Where arrayOfNums
is your array of values between 0 and 5.
The results are stored in a List<KeyValuePair>>
in the format you want.
You could improve upon this, instead of using the hardcoded 5
in the loop, you could use find the highest value in the array.
Upvotes: 0
Reputation: 457
var arrayOfNumbers = new int[] {1, 5, 4, 5, 1, 0, 2, 3, 4, 5, 1,1,1};
var result =
from n in arrayOfNumbers
group n by n into g
select new { Number = g.Key, Count = g.Count() };
foreach (var item in result)
{
Console.WriteLine(String.Format("Number {0}: count {1}", item.Number, item.Count));
}
Upvotes: 0
Reputation: 5890
You need to perform an outer join between your collection and a "fixed" collection containing numbers 0 to 5 first. Then group that and do the counting.
Upvotes: 2