Determine if two collections have at least one item

Is there a way to determine if a collection contains at least one element from another set?

+4
source share
3 answers

You can use Any ().

var listA = new List<int>(); var listB = new List<int>(); bool hasCommonItem = listA.Any(i => listB.Contains(i)); 

Alternatively, you can write IEqualityComparer to pass it as a parameter to Contains (), if necessary.

+9
source

Of course have.

 var sourceCollection = GetSourceCollection(); var otherCollection = GetAnotherCollection(); var hasAtLeastOne = sourceCollection.Intersect(sourceCollection).Any(); 

I assumed that your collections are of the same type: IEnumerable<T> with the same general parameter T

First it will load the whole sourceCollection , and then it will select one element at a time from the otherCollection until the first common one is found.

+8
source
 col1.Any(x => col2.Any(y => x==y)); 
0
source

All Articles