4

I have HahSet collection of int[9] arrays and want know if HashSe already contains that array. for example

       HashSet<int[]> set = new HashSet<int[]>();
       int[] a=new int[9]{1,2,3,4,5,6,7,8,9};
       set.Add(a);
       int[] a2=new int[9]{1,2,3,4,5,6,7,8,9};
       if(!set.Contains(a2))
          set.Add(a2);

How can I override or implement own Equals method so that HastSet.Contains would behave like Arrays.SequenceEquals?

Error
  • 815
  • 1
  • 19
  • 33

3 Answers3

5

You need to provide an implementation of IEqualityComparer<int[]>, and use the constructor that takes your custom comparer:

class MyEqCmpForInt : IEqualityComparer<int[]> {
    public bool Equals(int[] a, int[] b) {
        ...
    }
    public int GetHashCode(int[] data) {
        ...
    }
}

HashSet<int[]> set = new HashSet<int[]>(new MyEqCmpForInt());
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

The hash set class has a constructor that takes an equality comparer. Use it.

svick
  • 236,525
  • 50
  • 385
  • 514
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
2

You'll have to implement your own array-equality comparer, such as the one listed here.

And then it's as simple as asking the hash-set to use your comparer:

var set = new HashSet<int[]>(new ArrayEqualityComparer<int>());
...
    // You don't need to do a Contains check; it's implicit.
set.Add(someArray);
Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307