尝试从两个名单,其中获得不同的值; INT>对象 [英] Trying to get distinct values from two List<int> objects

查看:117
本文介绍了尝试从两个名单,其中获得不同的值; INT>对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个List对象:

I have 2 List objects:

List<int> lst1 = new List<int>();
List<int> lst2 = new List<int>();

让我们说,他们有值:

Let's say they have values:

lst1.Add(1);
lst1.Add(2);
lst1.Add(3);
lst1.Add(4);

lst2.Add(1);
lst2.Add(4);

我需要得到含有这两种的独特列表中的对象;所以在这种情况下,返回将是列表{2,3}

I need to get an object containing the "distinct" list of both of these; so in this case the return would be List {2, 3}.

有没有一种简单的方法来做到这一点?或者,我需要遍历列表的每个值和比较?

Is there an easy way to do this? Or do I need to iterate through each value of the lists and compare?

我打开使用的ObjectQuery,LINQ等等,因为这些表从数据库中来了,可能是几百到几千项长。

I am open to using ObjectQuery, LINQ, etc as these lists are coming from a database, and could potentially be several hundred to several thousand entries long.

谢谢!

推荐答案

艾哈迈德几乎是正确与除了,我相信 - 但是这不会给你这是项目在 LST2 而不是在 LST1 。所以,在这个例子中你给,如果添加5〜 LST2 ,我想你会希望得到的结果是{2,3,5}。在这种情况下,你想有一个对称差。我不的认为的有没有办法做到这一点直接在LINQ到对象在一个单一的电话,但你仍然可以实现它。下面是一个简单但低效的方式做到这一点:

Ahmad is nearly right with Except, I believe - but that won't give you items which are in lst2 but not in lst1. So in the example you gave, if you added 5 to lst2, I imagine you'd want the result to be {2, 3, 5}. In that case, you want a symmetric difference. I don't think there's any way to do that directly in LINQ to Objects in a single call, but you can still achieve it. Here's a simple but inefficient way to do it:

lst1.Union(lst2).Except(lst1.Intersect(lst2)).ToList();

(很明显,你只需要了ToList()如果你真的需要一个名单,其中,T&GT; 而不是一个的IEnumerable&LT; T&GT;

(Obviously you only need ToList() if you genuinely need a List<T> instead of an IEnumerable<T>.)

阅读这个问题的方法是:我想这是在任一列表中,但不是在这两个项目。

The way to read this is "I want items that are in either list but not in both."

这是可能的,这将是更有效地使用 Concat的 - 这将仍然为工作除了是一组根据运营商将只返回不同的结果:

It's possible that it would be more efficient to use Concat - which would still work as Except is a set based operator which will only return distinct results:

lst1.Concat(lst2).Except(lst1.Intersect(lst2)).ToList();

这篇关于尝试从两个名单,其中获得不同的值; INT&GT;对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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