检查存在于两个集合中的任何元素 [英] Check for any element that exists in two collections

查看:35
本文介绍了检查存在于两个集合中的任何元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Linq 是否有一种方法可以检查两个集合是否至少有一个共同的元素.我希望是这样的:

I'm wondering if Linq has a method to check if two collections have at least a single element in common. I would expect something like this:

var listA = new List<int>() { some numbers };
var listB = new List<int>() { some numbers, potentially also in list A };

bool hasSameElements = listA.hasMatchingElements(listB);

它是否存在于 Linq 中,或者我应该为它编写自定义方法吗?

Does it exists in Linq or should I write a custom method for it?

我知道 Intersect 方法,但这不会产生整个交集吗?我只对检查两个集合是否相交感兴趣,生成整个集合似乎是一种浪费,尤其是在较大的集合中.

I am aware of the Intersect method, but doesn't this yield the entire intersection set? I'm only interested in checking IF the two collection intersect, yielding the entire set seems like a waste, especially on larger collections.

推荐答案

听起来就像你想要的:

bool hasSameElements = listA.Intersect(listB).Any();

如评论中所述,Intersect 使用惰性求值.它推迟所有执行,直到从结果中读取第一个元素;在这一点上,它会将 listBall 加载到一个集合中,然后流式传输 listA 直到找到要产生的结果.那时,Any() 将返回 true,因此不会再做任何工作.请参阅我的 Edulinq发布在 Intersect 上以获取更多信息.

As noted in comments, Intersect uses lazy evaluation. It defers all execution until the first element is read from the result; at that point it will load all of listB into a set, and then stream listA until it finds a result to yield. At that point, Any() will return true and so no more work will be done. See my Edulinq post on Intersect for more information.

这篇关于检查存在于两个集合中的任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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