I have a List<IEnumerable<int>>
. I want to count how many occurrences of each IEnumerable<int>
there are in the list. For example:
using System.Linq;
List<IEnumerable<int>> list = new List<IEnumerable<int>>();
list.Add(new int[] { 5 }.AsEnumerable() );
list.Add(new int[] { 7, 8 }.AsEnumerable());
list.Add(new int[] { 5 }.AsEnumerable());
list.Add(new int[] { 5 }.AsEnumerable());
list.Add(new int[] { 9 }.AsEnumerable());
list.Add(new int[] { 4 }.AsEnumerable());
This list
has 3
IEnumerable<int>s
with value of 5
, and 1
occurrence of the other elements.
I've tried:
var one = list.ToArray().GroupBy(i => i).ToDictionary(x => x.Key.ToArray(), x => x.Count());
var two = list.GroupBy(x => x).Select(x => x).ToDictionary(x => x.Key, x => x.Count());
foreach(var item in one) { //or two
Console.WriteLine("key {0} .. item {1}",
string.Join(", ", item.Key.ToArray()),
item.Value);
}
Unfortunately both of these all result in 1
as the number of occurrences (even though the IEnumerable<int>s
with value of 5
have 3
occurrences).
Any suggestions to try?
EDIT
As MarcinJuraszek pointed out: "You'd have to define a custom comparer because default comparer for IEnumerable will do a reference equality." The reason I was getting all 1's was because it was searching the addresses in memory, which are all different. To get around this without writing a custom comparer I did this:
var dict = list.GroupBy(x => string.Format(", ", x.ToArray()) ).ToDictionary(x => x.Key, x => x.Count());