2

I have an List<Array>, I'm using LINQ to find duplicates and count, but it's not work. See the image you can see, lstMyList[0] and lstMyList[11] have the same value in Int[]

Here is lstMyList definition:

List<Array> lstMyList = new List<Array>();

I used code, but it's not work:

var group = lstMyList.GroupBy(t => t).ToArray();

or

Dictionary<int[], int> count = lstMyList.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());

Here is image: http://imageshack.com/a/img69/2552/h114.png

Maybe somebody can give me a hint about my problem.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
verygg
  • 23
  • 4
  • What is the `lstMyList` class definition? – Enigmativity Mar 31 '14 at 05:12
  • Having a key that is an `int[]` is probably not going to work for you. We need the class definition. – Enigmativity Mar 31 '14 at 05:13
  • declare lstMyList List lstMyList = new List(); or List lstMyList = new List(); – verygg Mar 31 '14 at 05:13
  • If you have two int arrays - both `int[] { 1, 2 }` - they are not equal to each other using standard equality as arrays are reference types and they only compare if the array is the same reference. Two arrays, even with the same values, are different. – Enigmativity Mar 31 '14 at 05:16
  • See about [Enumerable.GroupBy Method with IEqualityComparer](http://msdn.microsoft.com/ru-ru/library/bb534334(v=vs.110).aspx) – Grundy Mar 31 '14 at 05:22

2 Answers2

3

First create comparer class:

sealed class ArrayEqualityComparer : IEqualityComparer<int[]>
{
    public bool Equals(int[] x, int[] y)
    {
        if (x == null && y == null)
            return true;
        if (x != null && y != null)
            return x.SequenceEqual(y);
        return false;
    }

    public int GetHashCode(int[] obj)
    {
        return obj.Length;
    }
}

Then you can use it in GroupBy clause.

List<int[]> lstMyList = new List<int[]> { new[] { 1, 2 }, new[] { 3, 4 }, new[] { 1, 2 } };
var groups = lstMyList.GroupBy(t => t, new ArrayEqualityComparer())
                      .Select(g => new { g.Key, Count = g.Count() })
                      .ToArray();
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
  • 1
    It should be noted that this solution does have some potential drawbacks. The `g.Key` will be a reference to one of the "equal" arrays so careful if you modify the contents. Also the comparer will not equate `{1,2}` & `{2,1}` so, depending what the domain logic is, this could be an issue too. – Enigmativity Mar 31 '14 at 10:58
0

Try this

var group = lstMyList.GroupBy(t => t,
              StructuralComparisons.StructuralEqualityComparer).ToArray();
Aron
  • 15,464
  • 3
  • 31
  • 64