views:

241

answers:

1

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.

+18  A: 

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

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.

Jon Skeet
Very nice, clean way to handle this.
Reed Copsey
This is untested, but wouldn't return b.Except(a).Empty();be much more readable ?
Nils
Except that Empty() doesn't return a boolean. It returns an IEnumerable<T> with no items.
Peter Stephens
This requires Linq right? If so, I don't think that's available in Mono, which is what I'm using at the moment.
Matt Haley
You can use LINQ to Objects in Mono, I believe... but it would be helpful if you'd state the requirements in the question to start with. Which version of Mono are you using?
Jon Skeet
I've just checked the sources for Mono 2.4.2.3, and it definitely includes LINQ to Objects.
Jon Skeet
Confirmed this does work on Mono 2.4 when targeting 3.5.
Matt Haley