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
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()) ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With