为什么 .Except() 和 Intersect() 不能使用 LINQ 在这里工作?
我有以下代码,但似乎不起作用:
上下文: 我有两个对象列表:
* listOne 有 100 条记录
* listTwo 有 70 条记录,
其中许多记录具有相同的 Id 属性(在两个列表中);
var listOneOnlyItems = listOne.Except(listTwo, new ItemComparer ());
比较器
public class ItemComparer : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{
if (x.Id == y.Id)
return true;
return false;
}
public int GetHashCode(Item obj)
{
return obj.GetHashCode();
}
}
这是我运行此代码并查看结果后的
listOneOnlyItems
,仍然有 100 条记录(应该只有 30 条)。谁能帮助我吗?
此外,运行
IEnumerable<Item> sharedItems = listOne.Intersect(listTwo, new ItemComparer());
在sharedItems集合中返回零结果
i have the following code which doesnt seem to be working:
Context:
I have two lists of objects:
* listOne has 100 records
* listTwo has 70 records
many of them have the same Id property (in both lists);
var listOneOnlyItems = listOne.Except(listTwo, new ItemComparer ());
here is the comparer
public class ItemComparer : IEqualityComparer<Item>
{
public bool Equals(Item x, Item y)
{
if (x.Id == y.Id)
return true;
return false;
}
public int GetHashCode(Item obj)
{
return obj.GetHashCode();
}
}
after i run this code and look into the results
listOneOnlyItems
still has 100 records (should only have 30). Can anyone help me?
also, running
IEnumerable<Item> sharedItems = listOne.Intersect(listTwo, new ItemComparer());
returns zero reesults in the sharedItems collection
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
至少值得检查一下——IIRC GetHashCode() 在相等性之前首先被测试,如果它们没有相同的哈希值,则不会费心检查相等性。我不确定 obj.GetHashCode() 会发生什么——这取决于您在
Item
类上实现的内容。Worth a check at least -- IIRC GetHashCode() is tested first before equality, and if they don't have the same hash it won't bother checking equality. I'm not sure what to expect from
obj.GetHashCode()
-- it depends on what you've implemented on theItem
class.考虑让 GetHashCode() 返回 obj.Id.GetHashCode()
Consider making GetHashCode() return obj.Id.GetHashCode()
此代码工作正常:
您需要将“覆盖”关键字添加到 EqualityComparer 方法中。 (我认为没有将“覆盖”作为隐式是 C# 设计者的一个错误)。
This code works fine:
You need to add 'override' keywords to your EqualityComparer methods. (I think not having 'override' as implicit was a mistake on the part of the C# designers).