C# 如何确定两个 HashSet 是否相等(按值,而不是按引用)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/494224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:35:00  来源:igfitidea点击:

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

c#.net.net-3.5sethashset

提问by Craig W

I am trying to determine if two HashSetobjects 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.

我试图确定HashSet.NET 3.5 (C#) 中的两个对象是否是相等的集合,包含相同的值。这似乎是人们显然想要做的事情,但提供的功能似乎都没有为您提供此信息。

The way I can think to do this is by checking if the count of the two sets are equal andone 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 HashSethave a public bool IsEqualSetWith()function?

这总是有效吗?有没有更好的办法?为什么不HashSet具有 public bool IsEqualSetWith()的功能?

采纳答案by Michael Burr

Look at the method SetEquals.

查看方法SetEquals

my_hashset.SetEquals(other);

回答by Gregory Adam

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