Home > OS >  Checking if a list has all the contents of another
Checking if a list has all the contents of another

Time:12-04

Let's say I have a list of ints called List<int> List1 = new() {1,2,3,4} and List<int> List2 = new() {2,3,4}.

I need to check if List2 has everything List1 has. Keep in mind that list lengths may vary.

I have no idea on how to make it. Searching on the internet didnt really help.

CodePudding user response:

I would advise you to use HashSet for the first set of values and just iterate over the second one to check whether the iterator value exists in the created HashSet or not:

var set = new HashSet<int>(list1);
var result = list2.All(item => set.Contains(item));

If you don't want to use HashSet, you can do the same thing with LINQ, but with worse performance:

var result = list2.All(il2 => list1.Any(il1 => il1 == il2));

or

var result = !list2.Except(list1).Any();

CodePudding user response:

Here is the simple code, so you need to check whether ls2 is a subset of ls1.

bool isSubset = !ls2.Except(ls1).Any();
  • Related