0

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());
Mr Awesome8
  • 281
  • 4
  • 10
  • You'd have to define a custom comparer because default comparer for `IEnumerable` will do a reference equality. – MarcinJuraszek Dec 05 '16 at 20:18
  • @MarcinJuraszek, I think you already answered this question:http://stackoverflow.com/questions/15841178/group-by-array-contents – ocuenca Dec 05 '16 at 20:20
  • 1
    Something like `var results = list.SelectMany().GroupBy(x=>x).Select(x=>new {x.Key, x.Count});` – Robert McKee Dec 05 '16 at 20:36
  • @RobertMcKee That gives you the count of the number of values in inner sequences, not the number of sequences that are equal. – Servy Dec 05 '16 at 21:15
  • My bad, I thought that is what he wanted. I see now he's looking to group entire sequences and their count. – Robert McKee Dec 06 '16 at 03:15

0 Answers0