Alex Rivera | Logout

How to find if an element of a list is in another list?

Asked 2011-02-20T22:53:05.473
26

I want to know if at least one element in a first list can be found in a second list.

I can see two ways to do it. Let's say our lists are:

List<string> list1 = new[] { "A", "C", "F", "H", "I" };
List<string> list2 = new[] { "B", "D", "F", "G", "I" };

The first approach uses a loop:

bool isFound = false;
foreach (item1 in list1)
{
    if (list2.Contains(item1))
    {
        isFound = true;
        break;
    }
}

The second one uses Linq directly:

bool isFound = list1.Intersect(list2).Any();

The first one is long to write and not very straightforward/easy-to-read. The second one is short and clear, but performances will be low, especially on large lists.

What may be an elegant way to do it?

Edit
Report

2 Answers

23

The second one has better performance on large lists than the first one. Intersect puts the elements of one list into a hash table before checking the other list's elements for membership.

answered 2011-02-20T22:56:22.977
9

It seems odd to critique the performance of LINQ when the original is clearly (worst case) O(n*m); the LINQ approach would I expect use a HashSet<T> on a list, and then use a streaming iterator block - so the performance should be O(n+m) - i.e. better.

answered 2011-02-20T22:57:38.593

Your Answer