您如何确定两个HashSet是否相等(按值而不是按引用)? [英] How do you determine if two HashSets are equal (by value, not by reference)?
问题描述
我试图确定.NET 3.5(C#)中的两个 HashSet
对象是否相等,即包含相同的值。这似乎是人们显然想做的事情,但是所提供的功能似乎都没有给您提供此信息。
I am trying to determine if two HashSet
objects in .NET 3.5 (C#) are equal sets, i.e. contain the same values. 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
}
这将始终有效吗?有没有更好的办法?为什么 HashSet
没有的公共布尔IsEqualSetWith()
函数?
Would this always work? Is there a better way? Why doesn't HashSet
have a public bool IsEqualSetWith()
function?
推荐答案
查看方法 SetEquals 。
my_hashset.SetEquals(other);
这篇关于您如何确定两个HashSet是否相等(按值而不是按引用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!