0
using System.Linq;

var a = new byte?[][,]{
    new byte?[,]{{1}},
    new byte?[,]{{1}},
    new byte?[,]{{2}},
    new byte?[,]{{1, 2, 3}, {4, 5, 6}}};
a = a.Distinct().ToArray();

However 'a' still contains a duplicate. Am I doing this correctly?


Thanks. From the information in the answers.

class Nullable_Byte_2D_Array_EqualityComparer : IEqualityComparer<byte?[,]>
{
    public bool Equals(byte?[,] a, byte?[,] b)
    {
        var r = a.GetLength(0) == b.GetLength(0) &&
            a.GetLength(1) == b.GetLength(1);
        if (r)
        {
            var v = new byte?[a.Length];
            byte n = 0;
            foreach (byte? c in a)
            {
                v[n] = c;
                n++;
            }
            n = 0;
            foreach (byte? c in b)
            {
                if (c != v[n])
                    r = false;
                n++;
            }
        }
        return r;
    }
}

And

a = a.Distinct(new Nullable_Byte_2D_Array_EqualityComparer()).ToArray();
alan2here
  • 3,223
  • 6
  • 37
  • 62

1 Answers1

13

It doesn't contain a duplicate. It contains two distinct arrays which happen to have the same values inside of them. Since arrays are reference types, Distinct() does a reference comparison by default; to change this behavior, use this override to specify your own comparer.

Cole Campbell
  • 4,846
  • 1
  • 17
  • 20
  • How is this applied to my example? So It's about implementing .Equals() for the type I'm using, except I'm using Array, so I need to override just [,] 2D types of Array? – alan2here Jul 30 '12 at 20:41
  • 1
    You need to create a class that implements `IEqualityComparer` and pass an instance of it into `Distinct()`. See the MSDN documentation for more info: http://msdn.microsoft.com/en-us/library/ms132151.aspx – Cole Campbell Jul 30 '12 at 20:43