Does .NET have a way to check if List a contains all items in List b?

If you’re using .NET 3.5, it’s easy:

public class ListHelper<T>
{
    public static bool ContainsAllItems(List<T> a, List<T> b)
    {
        return !b.Except(a).Any();
    }
}

This checks whether there are any elements in b which aren’t in a – and then inverts the result.

Note that it would be slightly more conventional to make the method generic rather than the class, and there’s no reason to require List<T> instead of IEnumerable<T> – so this would probably be preferred:

public static class LinqExtras // Or whatever
{
    public static bool ContainsAllItems<T>(this IEnumerable<T> a, IEnumerable<T> b)
    {
        return !b.Except(a).Any();
    }
}

Leave a Comment