简体   繁体   English

如何确定两个HashSets是否相等(按值,而不是通过引用)?

[英]How do you determine if two HashSets are equal (by value, not by reference)?

I am trying to determine if two HashSet objects in .NET 3.5 (C#) are equal sets, ie contain the same values. 我试图确定.NET 3.5(C#)中的两个HashSet对象是否是相等的集合, 包含相同的值。 This seems like something one would obviously want to do but none of the provided functions seem to give you this information. 这似乎是人们显然想做的事情,但是所提供的功能似乎都没有给你这些信息。

The way I can think to do this is by checking if the count of the two sets are equal and one set is a subset (not proper) of the other. 我能想到这样做的方法是检查两组的计数是否相等一组是另一组的子集(不合适)。 I think the only way that can happen is if they are equal sets. 我认为唯一可能发生的方法是它们是否相同。 Example code: 示例代码:

HashSet<int> set1 = new HashSet<int>();
set1.Add(1);
set1.Add(2);
set1.Add(3);

HashSet<int> set2 = new HashSet<int>();
set2.Add(1);
set2.Add(2);
set2.Add(3);

if(set1.Count == set2.Count && set1.IsSubsetOf(set2))
{
    // do something
}

Would this always work? 这会一直有效吗? Is there a better way? 有没有更好的办法? Why doesn't HashSet have a public bool IsEqualSetWith() function? 为什么HashSet没有public bool IsEqualSetWith()函数?

看看方法SetEquals

my_hashset.SetEquals(other);
IEqualityComparer<HashSet<int>> comp = HashSet<int>.CreateSetComparer();
Console.WriteLine("CreateSetComparer set1 == set2 : {0}", comp.Equals(set1, set2));
// or
bool areEqual = HashSet<int>.CreateSetComparer().Equals(set1, set2);

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

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