How do I know if at least one element in a list is contained in another list?

7

I have two lists:

var lista01 = new List<int> { 1, 2, 3, 4, 5 };
var lista02 = new List<int> { 7, 7, 7, 7, 7 };

I need to check if at least one element of list 1 exists in list 2, so the result for the above example should be false.

But if my list is:

var lista01 = new List<int> { 1, 2, 3, 4, 5 };
var lista02 = new List<int> { 5, 7, 7, 7, 7 };

I want the result to be true.

How can I do this?

    
asked by anonymous 24.12.2013 / 23:54

1 answer

8

There are some methods in linq that can help you do this:

Intersect

If the result of an intersection results in 1 or more elements means that at least one is equal.

var resultado = lista01.Intersect(lista02);
bool existeElementoIgual = resultado.Any();

I recommend using this method.

You can pass IEqualityComparer<T> as the second parameter if you need to compare more complex objects.

Except

If the result of an exclusion contains fewer elements than the total, then at least one element is equal.

var resultado = lista01.Except(lista02);
bool existeElementoIgual = resultado.Count() != lista01.Count;

You can pass IEqualityComparer<T> as the second parameter if you need to compare more complex objects.

Any

If any element of list 1 is equal to any element of list 2 it means that there is an element equal.

bool existeElementoIgual = lista01.Any(e => lista02.Any(o => o == e));

Any and IndexOf

If any element of list 1 is found in list 2 it means that there is an element equal.

bool existeElementoIgual = lista01.Any(e => lista02.IndexOf(e) != -1);

The disadvantage of IndexOf is that it makes it impossible to compare objects from any inline property, since it uses EqualityComparer<T>.Default .

Performance

In a large list, lista01.Any(e => lista02.Any(o => o == e)) will perform very well only if the value contained in the second list is at the beginning of the first list. Otherwise this method will be extremely slow, as it cycles through list 1 sequentially and for each object in list 1 it traverses list 2 sequentially.

In a performance test I obtained the following results:

Lists with 5 elements each, test 10000000 times.

Intersect     : 00:00:02.9260135
Except        : 00:00:03.4404527
AnyAny        : 00:00:06.5709693
AnyIndexOf    : 00:00:01.9882278

Lists with 100000 elements each, test 500 times. Element of the third position of list01 is equal to the last element of list02.

Intersect     : 00:00:02.4397784
Except        : 00:00:04.2595364
AnyAny        : 00:00:02.9761128
AnyIndexOf    : 00:00:00.0919344

Lists with 100000 elements each, test 500 times. The last element in list01 is the same as the last element in list02.

Intersect     : 00:00:02.4927969
Except        : 00:00:04.2668677
AnyAny        : mais de um minuto e teste encerrado
AnyIndexOf    : mais de um minuto e teste encerrado
    
24.12.2013 / 23:54