Check for any element that exists in two collections

C#LinqCollections

C# Problem Overview


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

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.

C# Solutions


Solution 1 - C#

Sounds like you just want:

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

EDIT: 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzeebonkView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow