Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

c# - Check for any element that exists in two collections

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...