Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how can i determine if a list has any item from another list?

I have a list:

var list = new List<string>();
list.Add("Dog");
list.Add("Cat");
list.Add("Bird");

var list2 = new List<string>();
list2.Add("Dog");
list2.Add("Cat"):

if (list.ContainsAny(list2))
{
      Console.Write("At least one of the items in List2 exists in list1)"
}
like image 347
leora Avatar asked Oct 29 '13 02:10

leora


2 Answers

You're looking to see if the "Intersection" of the lists is non-empty:

if(list.Intersect(list2).Any())
    DoStuff();
like image 163
Servy Avatar answered Oct 30 '22 00:10

Servy


You simply need Enumerable.Intersect as below:

if (list.Intersect(list2).Any())
{
  Console.Write("At least one of the items in List2 exists in list1)"
}

This method produces the set intersection of two sequences by using the default equality comparer to compare values. It returns a sequence that contains the elements that form the set intersection of two sequences.The Enumerable.Any() method determines whether a sequence contains any elements.

like image 24
Bhushan Firake Avatar answered Oct 29 '22 22:10

Bhushan Firake