I have two IEnumerable<string>
that represent lists of strings. I want to see if any element in the first set matches any element in the second set. At the moment I have something that looks like this:
firstSet.Intersect(secondSet).Count() > 0
However, it seems to me to be rather inefficient because it will produce a list of the elements that match, then count them all. I can then test to 开发者_JAVA百科see if the count is greater than zero. I don't care about which match, how many match, just that any element in the two sets match. Is there anything like firstSet.AnyMatch(secondSet)
that I'm missing?
Is there a more efficient way to express that?
Use Any
instead:
if (firstSet.Intersect(secondSet).Any())
I believe this will build of hash set of the second collection first (in its entirety) and then iterate over the first set until it finds a match or runs out of elements to test. You may wish to bear this in mind when working out which way round to put firstSet
and secondSet
.
EDIT: Just to repeat what's already in a comment... if you know that (say) firstSet
is a HashSet<string>
then you should cast to it and use Overlaps
:
HashSet<string> firstHashSet = (HashSet<string>) firstSet;
if (firstHashSet.Overlaps(secondSet))
{
...
}
精彩评论