简体   繁体   English

比较嵌套哈希集的相等性

[英]Comparing equality of nested hashsets

I have a situation where I need to compare the equality of nested hashsets to determine if they contain the same elements or not. 我遇到一种情况,需要比较嵌套哈希集的相等性,以确定它们是否包含相同的元素。 Here is a quick example that illustrates the problem: 这是一个说明问题的简单示例:

    public void HashsetComparison()
    {
        var set1 = new HashSet<string> { "A", "B", "C" };
        var set2 = new HashSet<string> { "B", "C", "A" };
        var set3 = new HashSet<string> { "D", "E" };
        var set4 = new HashSet<string> { "D", "E" };

        //both currently return true
        var test1 = set1.SetEquals(set2);
        var test2 = set3.SetEquals(set4);

        var set5 = new HashSet<HashSet<string>> { set1, set3 };
        var set6 = new HashSet<HashSet<string>> { set2, set4 };

        //currently returns false
        var test3 = set5.SetEquals(set6);
    }

I need to figure out what to change in order to get test3 to return true. 我需要弄清楚要更改什么才能使test3返回true。 From the debugging that I have done, it seems like the HashSet.SetEquals() method is asking its children to get their hash codes and using those to compare for equality, which makes sense. 从我完成的调试中,似乎HashSet.SetEquals()方法正在要求其子代获取其哈希码,并使用其哈希码进行相等性比较,这很有意义。

I've looked through some of the similar questions on StackOverflow, but haven't found one that has completely explained it to me yet. 我已经研究了StackOverflow上的一些类似问题,但是还没有找到一个完全向我解释过的问题。 Do I need to implement a custom IEqualityComparer for the HashSet or is there something more obvious that I'm doing incorrectly? 我是否需要为HashSet实现自定义IEqualityComparer,或者是否有其他明显的方法在做错误的事情?

When you create the sets of sets, you're not providing a comparer, so the default comparer will be used, which will compare the sets based on their references. 创建集合集时,没有提供比较器,因此将使用默认比较器,它将基于它们的引用来比较集合。 The use of SetEquals will uses the comparers of the sets, rather than allowing a comparer to be passed to those methods. SetEquals的使用将使用集合的比较器,而不是允许将比较器传递给那些方法。

You need to pass a comparer to these two sets that compares them based on their values, rather than their references. 您需要将比较器传递给这两个集合,以便根据它们的值而不是它们的引用对它们进行比较。 Fortunately HashSet<T> already provides a method to create such a comparer: 幸运的是, HashSet<T>已经提供了创建这种比较器的方法:

var set5 = new HashSet<HashSet<string>>(HashSet<string>.CreateSetComparer()) 
{ set1, set3 };
var set6 = new HashSet<HashSet<string>>(HashSet<string>.CreateSetComparer()) 
{ set2, set4 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM