How to implement your own HashSet method

I have a collection of int [9] HahSet arrays and want to know if HashSe contains this array. eg

       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 my own Equals method so that HastSet.Contains behaves like Arrays.SequenceEquals?

+3


source to share


3 answers


You need to provide an implementation IEqualityComparer<int[]>

and use a constructor that accepts your custom mapper:



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

HashSet<int[]> set = new HashSet<int[]>(new MyEqCmpForInt());

      

+5


source


In a hash set class, a constructor that accepts an equality matcher . Use it.



+4


source


You will have to implement your own versus array matcher like the one listed here .

And then it's as easy as asking a hash set to use your comparator:

var set = new HashSet<int[]>(new ArrayEqualityComparer<int>());
...
    // You don't need to do a Contains check; it implicit.
set.Add(someArray);

      

+2


source







All Articles