C# 如何实现自己的HashSet包含方法

C# 如何实现自己的HashSet包含方法,c#,C#,我有一组int[9]数组,我想知道HashSe是否已经包含了这个数组。 比如说 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))

我有一组int[9]数组,我想知道HashSe是否已经包含了这个数组。 比如说

       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);
HashSet=newhashset();
int[]a=新的int[9]{1,2,3,4,5,6,7,8,9};
增加(a);
int[]a2=新的int[9]{1,2,3,4,5,6,7,8,9};
如果(!集合包含(a2))
增加(a2);

如何重写或实现own Equals方法,使HastSet.Contains的行为类似于Arrays.SequenceEquals?

哈希集类具有。使用它。

您需要提供一个
IEqualityComparer
的实现,并使用获取自定义比较器的构造函数:

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

HashSet<int[]> set = new HashSet<int[]>(new MyEqCmpForInt());
var set = new HashSet<int[]>(new ArrayEqualityComparer<int>());
...
    // You don't need to do a Contains check; it's implicit.
set.Add(someArray);
MyEqCmpForInt类:IEqualityComparer{
公共布尔等于(int[]a,int[]b){
...
}
公共int GetHashCode(int[]数据){
...
}
}
HashSet set=newhashset(newmyeqcmpforint());

您必须实现自己的数组相等比较器,如所列的数组相等比较器

然后,只需让哈希集使用比较器即可:

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

HashSet<int[]> set = new HashSet<int[]>(new MyEqCmpForInt());
var set = new HashSet<int[]>(new ArrayEqualityComparer<int>());
...
    // You don't need to do a Contains check; it's implicit.
set.Add(someArray);
var set=new HashSet(new ArrayEqualityComparer());
...
//你不需要做包含检查;这是含蓄的。
set.Add(someArray);