问题描述
List1
包含项目 { A, B }
和 List2
包含项目 { A, B, C }
.
List1
contains items { A, B }
and List2
contains items { A, B, C }
.
我需要的是返回 { C }
当我使用 Ext Linq 扩展时.相反,我得到了返回 { A, B }
并且如果我在表达式中翻转列表,结果是 { A, B, C }
.
What I need is to be returned { C }
when I use Except Linq extension. Instead I get returned { A, B }
and if I flip the lists around in my expression the result is { A, B, C }
.
我是不是误解了例外"的意思?有没有其他扩展我没有看到使用?
Am I misunderstanding the point of Except? Is there another extension I am not seeing to use?
到目前为止,我已经浏览并尝试了许多关于此问题的不同帖子,但都没有成功.
I have looked through and tried a number of different posts on this matter with no success thus far.
var except = List1.Except(List2); //This is the line I have thus far
是的,我正在比较简单的对象.我从未使用过 IEqualityComparer
,学习起来很有趣.
Yes I was comparing simple objects. I have never used IEqualityComparer
, it was interesting to learn about.
感谢大家的帮助.问题不在于实现比较器.以下链接的博客文章和示例有帮助.
Thanks all for the help. The problem was not implementing the comparer. The linked blog post and example below where helpful.
推荐答案
如果您在列表中存储引用类型,您必须确保有一种方法可以比较对象的相等性.否则将通过比较它们是否引用相同的地址来检查它们.
If you are storing reference types in your list, you have to make sure there is a way to compare the objects for equality. Otherwise they will be checked by comparing if they refer to same address.
您可以实现 IEqualityComparer
并将其作为参数发送到 Except() 函数.这是一个 博客发帖你可能会觉得有帮助.
You can implement IEqualityComparer<T>
and send it as a parameter to Except() function. Here's a blog post you may find helpful.
编辑:原始博文链接 已损坏并已在上面替换
edit: the original blog post link was broken and has been replaced above
这篇关于使用 Linq 除了不像我想的那样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!