Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How implement own HashSet contains method

Tags:

c#

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?

like image 312
Error Avatar asked Dec 20 '22 09:12

Error


2 Answers

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());
like image 55
Sergey Kalinichenko Avatar answered Jan 09 '23 00:01

Sergey Kalinichenko


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

like image 21
Eric Lippert Avatar answered Jan 08 '23 23:01

Eric Lippert