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

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

问题描述

我不知道是否有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?

我知道相交方法,但不这样得到整个交集?我只是在检查,如果两个集合相交,产生整组等的浪费看来,特别是在较大的收藏兴趣。

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();



编辑:正如在评论中指出,相交使用懒评价。它推迟的所有的执行,直到第一个元素是从结果看;在这一点上它会加载的所有数组listB 成一组,并再流为listA 直到它找到一个结果产生。在这一点上,<​​code>任何()将返回真正键,所以没有更多的工作要做。看到我的 Edulinq关于发布相交 了解详情。

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天全站免登陆