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

Viewed 86582

I have the following method:

namespace ListHelper
{
    public class ListHelper<T>
    {
        public static bool ContainsAllItems(List<T> a, List<T> b)
        {
            return b.TrueForAll(delegate(T t)
            {
                return a.Contains(t);
            });
        }
    }
}

The purpose of which is to determine if a List contains all the elements of another list. It would appear to me that something like this would be built into .NET already, is that the case and am I duplicating functionality?

Edit: My apologies for not stating up front that I'm using this code on Mono version 2.4.2.

5 Answers

I know a way using LinQ methods. It's a bit weird to read, but works pretty well

var motherList = new List<string> { "Hello", "World", "User };
var sonList = new List<string> { "Hello", "User" };

You want to check if sonList is totally in motherList

To do so:

sonList.All(str => moterList.Any(word => word == str));

// Reading literally, would be like "For each of all items 
// in sonList, test if it's in motherList

Please check it on and see if works there too. Hope it helps ;-)

Related