Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<string> "contains" question

Is there an easy way, either through LINQ or Generics, to find out if elements in one List are all available in another List.

I'm currently using Intersect to check this.

For e.g.

List<string> list1; //{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }

List<string> list2; //{ 1, 3, 9 }

list1.Contains(list2) == true

Thanks in advance

like image 949
Ganesha Avatar asked Dec 30 '25 09:12

Ganesha


2 Answers

The Intersect method will give you all the elements that are in both lists.

E.g.

var inboth = list1.Intersect(list2);

or if you just want to know if there are any shared elements between the two

if(list1.Intersect(list2).Any()) ...
like image 189
Brian Rasmussen Avatar answered Jan 02 '26 08:01

Brian Rasmussen


Intersect is a good way to do it. The only other reasonable way is to just brute-force it:

list2.All(x => list1.Contains(x));

Note that neither technique will work if, for example, list2 is (1 2 2) and list1 is (1 2 3) and you want that to return false. If you needed to check that, I would sort both lists and walk down them together.

like image 27
mqp Avatar answered Jan 02 '26 08:01

mqp