There are some methods in Lille that can help you do this:
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 the use of this method.
It is possible to pass a IEqualityComparer<T>
as second parameter if it is necessary to compare more complex objects.
If the result of an exclusion contains fewer elements than the total means that at least one element is equal.
var resultado = lista01.Except(lista02);
bool existeElementoIgual = resultado.Count() != lista01.Count;
It is possible to pass a IEqualityComparer<T>
as second parameter if it is necessary to compare more complex objects.
If any element in list 1 is equal to any element in list 2 it means that there is an equal element.
bool existeElementoIgual = lista01.Any(e => lista02.Any(o => o == e));
If any element from list 1 is found in list 2 it means that there is an equal element.
bool existeElementoIgual = lista01.Any(e => lista02.IndexOf(e) != -1);
The disadvantage of IndexOf
is that it makes it impossible to compare objects from any property inline, because he uses EqualityComparer<T>.Default
.
Performance
On a big list, lista01.Any(e => lista02.Any(o => o == e))
will have a very good performance 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 goes through the list 1 sequentially and for each object in the list 1 it goes through the list 2 sequentially.
In a performance test I got 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 the list01 is equal to the last element of the 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. Last element of the list01 is equal to the last element of the 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