我有一个列表,我想过滤重复项。在问这个问题之前我在 StackOverflow 上搜索并找到了两个解决方案;使用 .Distinct()
和使用 HashSet
,但是这些方法都不适合我。我试图过滤的对象实现了 .Equals
方法,但它仍然不起作用。
我通过创建 500 个完全相同的对象并将它们放在列表中来测试这一点。我预计会剩下 1 个,但所有 500 个都还在。我的对象是否需要实现额外的方法才能工作?
谢谢。
最佳答案
如果您覆盖 Equals
总是也覆盖 GetHashCode
。
Why is it important to override GetHashCode when Equals method is overridden?
这是一个简单的类来演示可能的实现。 GetHashCode
应该是高效的并且应该产生很少的冲突:
public class Foo
{
public int ID { get; set; }
public string Name { get; set; }
public override bool Equals(object obj)
{
Foo other = obj as Foo;
if (other == null) return false;
return this.ID == other.ID;
}
public override int GetHashCode()
{
return ID;
}
}
Here's 另一个实现,如果您的相等性检查需要包含多个属性或集合:
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
}
关于c# - 过滤列表中的重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20002422/