In C #, how can I determine if a list has an 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)" } 
+6
source share
2 answers

You want to see if the "Intersection" of the lists is:

 if(list.Intersect(list2).Any()) DoStuff(); 
+18
source

You just need Enumerable.Intersect as shown below:

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

This method creates multiple intersections of two sequences using the default equalizer to compare values. It returns a sequence containing elements that form the set of intersections of two sequences. The Enumerable.Any () method determines whether the sequence contains any elements.

0
source

Source: https://habr.com/ru/post/956910/


All Articles