【问题标题】:HashSet on collections of objects [duplicate]对象集合上的HashSet [重复]
【发布时间】:2020-12-12 00:07:31
【问题描述】:
我有一个T 类型的对象,它实现了IEquatable<T>(实现了方法Equals 和GetHashCode)。我在HashSet<T> 中使用这些对象。但是对于我的开发,我需要将此哈希集的元素升级为T 对象的集合(列表或数组都可以工作,例如我将使用HashSet<List<T>>)。这些集合(例如List<T>)具有默认的Equals 和GetHashCode 方法,但是我如何覆盖它们以便当且仅当它们顺序相等时才说两个集合相等?以及如何获得合适的GetHashCode?此功能是否已经以某种方式存在于 .Net 中?例如,我可以定义一个新类型 TT 来包装 List<T>,并实现 IEquatable<TT> 并在 Equals 方法中使用 Enumerable.SequenceEqual。但是GetHashCode 呢?谢谢!
【问题讨论】:
标签:
c#
.net
hashset
gethashcode
【解决方案1】:
HashSet<T> 有一个constructor which takes an IEqualityComparer<T>。您可以使用它来自定义 HashSet<T> 比较其元素的方式。
类似:
public class ListEqualityComparer<T> : IEqualityComparer<List<T>>
{
public bool Equals(List<T> x, List<T> y)
{
if (x is null && y is null)
return true;
if (x is null || y is null)
return false;
return x.SequenceEqual(y);
}
public int GetHashCode(List<T> obj)
{
if (obj is null)
return 0;
var hashCode = new HashCode();
foreach (var item in obj)
{
hashCode.Add(item);
}
return hashCode.ToHashCode();
}
}
然后:
var hashSet = new HashSet<List<YourType>>(new ListEqualityComparer<YourType>());