InsqThew
InsqThew

Reputation: 597

LINQ: Query if collection contains any element in another collection

So obviously this is easily doable with a couple of foreach loops, but I just started using C# after years of Java and now I'm trying to stuff LINQ into everything because it's so awesome.

I have two ICollections of strings, and I want to check if one collection contains any of the strings in the other one. Put another way, I want to check if the union of the two collections is empty or not.

In this case I'm not actually concerned with WHICH strings match, just whether a match exists or not. I'm assuming Any is the key method here, but I can't figure out how to do what I want with it. I'm sure the solution's pretty simple; I'm just not very familiar with building queries.

Upvotes: 34

Views: 13833

Answers (1)

SLaks
SLaks

Reputation: 887433

if (a.Intersect(b).Any())

Upvotes: 72

Related Questions