整数数组哈希集的 C# 结构比较

本文关键字:结构 比较 数组 哈希集 整数 | 更新日期: 2023-09-27 18:29:12

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);

是否有一个(默认的?(比较器我可以插入到HashSet中,以便s1。等于(s2(是真的吗?我知道有一个StructuralComparisons.StructuralEqualityComparer,但HashSet需要一个通用的IEqualityComparer<>。

更新:

看起来永远行不通。我得到的最接近的是使用HashSet.SetEquals并插入StructuralComparisons.StructuralEqualityComparer的包装器,如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;
    }

然后

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

整数数组哈希集的 C# 结构比较

否 - 因为

隐式数组相等性的定义不会超出参考质量;在运行时,数组不会提供考虑内部元素的GetHashCode - 因为,正确地,没有组合哈希代码的一般情况 - 所以框架不会尝试实现一个。

你必须自己滚。

不,默认没有比较器,但您可以创建这样的扩展方法,该方法可以解决问题:

public static class HashSetExt
{
    public static bool HashSetEqualsTo<T>(this HashSet<T> set, HashSet<T> other)
    {
        return //Your own compare method
    }
}
class Program
{
    static void Main(string[] args)
    {
        var s1 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } });
        var s2 = new HashSet<int[]>(new[] { new[] { 1, 2 }, new[] { 3, 4 } });
        var isEquals = s1.HashSetEqualsTo<int[]>(s2);
    }
}