Ceken
Ceken

Reputation: 3

What is the quickest method to find is there intersect between two list?

I have written a code to check intersection between two list. I need only is there intersection. Is there a quicker way for it.

L,L2 are List<int>

bool working = true;

bool ok=false;
for (int k = 0; k<L.Count && working;k++) {
   if (L2.Any (a => a == L[k])) {
      ok=true;//There is an integer in L and   L2
      working=false;
   }
}

Upvotes: 0

Views: 54

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

Not sure if i have overlooked something, but normally you'd use Intersect+Any:

bool intersects = L.Intersect(L2).Any();

This works if the type in the list overrides Equals and GetHashCode like most .NET classes do. If you use your own you should remember that, otherwise only references are compared.

Upvotes: 1

Related Questions