tags:

views:

169

answers:

3

I have two lists

List 01 => { A, B, C, D, E }
List 02 => { F, F, F, F, E }

I need to check if one element of List 02 exists in List 01, so the following should be false.

List 01 => { A, B, C, D, E }
List 02 => { F, F, F, F, F } // no element matches

And here it should be true.

List 01 => { A, B, C, D, E }
List 02 => { F, F, F, F, B } // last element matches

How can I check that?

I'm concerned about performance as well.

+3  A: 

try

list1.Any(e => list2.Contains(e));

e.g.

var list1 = new List<string> { "A", "B", "C", "D" };
var list2 = new List<string> { "F", "F", "F" };

list1.Any(e => list2.Contains(e)); // returns false

var list3 = new List<string> { "F", "F", "D" };

list1.Any(e => list3.Contains(e)); // returns true

UPDATE: as leppie points out, using Intersect will be more performant, esp if the lists are large.

theburningmonk
While the solution is correct, this will run in O(n^2) whereas the other methods (as mentioned by me) will run in O(n).
leppie
+5  A: 

Enumerable.Except & Enumerable.Intersect.

leppie
Thanks for your comment on the other answer. I've tested it with two lists of size `1000`. Using `Intersect` against `Any` and `Contains`, the result was ~1300 ticks vs ~32000 ticks (tested using Stopwatches).
BrunoLM
+11  A: 
list1.Intersect(list2).Any()

This will be most performant as it uses HashSets.

Tim