Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# structural comparison of hashsets of int arrays

Tags:

c#

collections

var comparer = ...
var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer);
var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer);

Is there a (default?) comparer I can plug into HashSet so that s1.Equals(s2) is true? I know there is a StructuralComparisons.StructuralEqualityComparer, but HashSet requires a generic IEqualityComparer<>.

UPDATE:

Doesn't look like it could ever work. The closest I get is to use HashSet.SetEquals and plug in a wrapper for StructuralComparisons.StructuralEqualityComparer as suggested by phoog

    internal class GenericStructuralComparer<T> : IEqualityComparer<T>
    {
        static GenericStructuralComparer<T> _instance;

        public static IEqualityComparer<T> Instance
        {
            get { return _instance ?? (_instance = new GenericStructuralComparer<T>()); }
        }

        public bool Equals(T x, T y)
        {
            return StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
        }

        public int GetHashCode(T obj)
        {
            return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
        }
    }

    public static IEqualityComparer<T> StructuralComparer<T>()
    {
        return GenericStructuralComparer<T>.Instance;
    }

And then

var comparer = StructuralComparer<int[]>();
var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer);
var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } }, comparer);
s1.SetEquals(s2); // True
like image 560
jvdneste Avatar asked Oct 19 '25 10:10

jvdneste


1 Answers

No - because implicit array equality is not defined beyond reference quality; and at runtime an array won't provide a GetHashCode that will take into account the inner elements - because, correctly, there's no general case for combining hashcodes - so the framework doesn't try to implement one.

You'll have to roll your own.

like image 118
Andras Zoltan Avatar answered Oct 22 '25 00:10

Andras Zoltan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!