find if list contain all items of other list in csharp

One way to check if a list contains all items of another list in C# is by using the Enumerable.Intersect method. This method returns the intersection of two sequences, which is a sequence that contains the common elements of both sequences.

Here's an example code that demonstrates how to use Enumerable.Intersect to check if a list contains all items of another list:

main.cs
List<int> list1 = new List<int> { 1, 2, 3 };
List<int> list2 = new List<int> { 1, 3 };

bool containsAll = !list2.Except(list1).Any();

if (containsAll)
{
    Console.WriteLine("list1 contains all items of list2");
}
else
{
    Console.WriteLine("list1 does not contain all items of list2");
}
294 chars
14 lines

In this example, we have two lists list1 and list2. We want to check if list1 contains all items of list2.

We first use the Except method to get the items in list2 that are not in list1. We then use the Any method to check if there are any items in the result. If the result is empty, it means that list1 contains all items of list2.

Finally, we use the ! operator to negate the result, so that containsAll is true if list1 contains all items of list2.

related categories

gistlibby LogSnag