【发布时间】:2015-09-09 07:53:15
【问题描述】:
我有两个列表List<MyClass>:
public class MyClass : IEquatable<MyClass>
{
public string AccountNumber { get; set; }
public int ID { get; set; }
public int AccountType { get; set; }
public bool Equals(MyClass other)
{
if (other == null) return false;
if (object.ReferenceEquals(this, other))
return true;
return AccountNumber.Equals(other.AccountNumber) && AccountType.Equals(other.AccountType);
}
public override int GetHashCode()
{
int hashAccountNumber = AccountNumber == null ? 0 : AccountNumber.GetHashCode();
int hashType = AccountType.GetHashCode();
return hashAccountNumber ^ hashType;
}
}
如果我使用以下代码
var list1 = new List<MyClass>()
{
new MyClass() { AccountNumber = "1", AccountType = 1, ID = 1},
new MyClass() { AccountNumber = "1", AccountType = 1, ID = 2},
new MyClass() { AccountNumber = "2", AccountType = 1, ID = 3},
new MyClass() { AccountNumber = "3", AccountType = 1, ID = 4}
};
var list2 = new List<MyClass>()
{
new MyClass() { AccountNumber = "1", AccountType = 1, ID = 1 }
};
var alist = list1.Intersect(list2).ToList();
alist 只有 1 个元素,其中 MyClass.ID == 1。它不返回也匹配的第二个。我也可以反过来 var alist = list2.Intersect(list1).ToList(); 得到同样的结果
我的IEquatable 实现有问题吗?因为我不确定我做错了什么。或者这就是IEnumerable 的工作方式?有没有另一种方法可以用来从 list1 返回所有匹配的元素?我真的希望有:)
【问题讨论】:
-
旁注:如果你正在实现
IEquatable<T>并覆盖GetHashCode,你也应该覆盖Equals(object other)。 -
@Damien_The_Unbeliever 我无法覆盖
Equals。Error 1 'MyClass.Equals(MyClass)': no suitable method found to override当我添加覆盖时。如果我使用与IEquatable相同的签名,我不应该覆盖Equals吗?相反,我使用了类类型,因此我用类类型重载了 Equals。如果您认为它不正确,请告诉我。 -
您应该有 两个 Equals 方法 - 一个接受您当前拥有的
MyClass。 other 应该是Object.Equals(Object)方法的覆盖。请参阅IEquatable.Equals 的文档中的示例 -
@Jaques BTW 我觉得你的问题是一个 XY 问题。我不明白为什么十字路口不适合你。为什么你想要同一个对象出现两次?
-
因为对象不是 100% 相同的。我有一个缩短版的课程。仅使用 2 个属性来判断它是否是同一种对象,但其他属性使其唯一。我希望它们都在一个列表中,因为我必须如何构建输出
标签: c# ienumerable