使用LINQ除了没有工作,因为我以为 [英] Using Linq Except not Working as I Thought

查看:173
本文介绍了使用LINQ除了没有工作,因为我以为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List1中包含项目{A,B}和列表2包含项目{A,B,C}。

List1 contains items { A, B } and List2 contains items { A, B, C }.

我需要的是要返回{c}里,当我使用LINQ的除外延伸。而我得到回来{A,B},如果我在我的前pression左右翻转列出的结果是{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除= List1.Except(列表2); //这是我行迄今

编辑:是的,我是比较简单的对象。我从来没有使用过的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&LT; T&GT; ,并把它作为一个参数的除了()功能。这里有一个<一个href="http://blogs.msdn.com/b/csharpfaq/archive/2009/03/25/how-to-use-linq-methods-to-compare-objects-of-custom-types.aspx"相对=nofollow>博客文章对您有帮助。

You can implement IEqualityComparer<T> and sent it as a parameter to Except() function. Here's a blog post you may find helpful.

这篇关于使用LINQ除了没有工作,因为我以为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆