.NET has a way to check if List a contains all the elements in list b?

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 this is to determine if List contains all the elements of another list. It seems to me that something like this will be built into .NET already, is that the case, and am I duplicating functionality?

Edit: I apologize for not using this code in Mono version 2.4.2.

+76
list generics c # mono
Oct 05 '09 at 15:02
source share
4 answers

If you are using .NET 3.5, this is easy:

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

This checks to see if there are any elements in b that are not in a and then inverts the result.

Note that it would be a little more familiar to make the method universal rather than a class, and there is no reason to require a List<T> instead of an IEnumerable<T> - so this would probably be preferable:

 public static class LinqExtras // Or whatever { public static bool ContainsAllItems<T>(this IEnumerable<T> a, IEnumerable<T> b) { return !b.Except(a).Any(); } } 
+145
Oct 05 '09 at 15:06
source share

Just for fun, @JonSkeet answer as an extension method:

 /// <summary> /// Does a list contain all values of another list? /// </summary> /// <remarks>Needs .NET 3.5 or greater. Source: /questions/83422/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b/548327#548327 </remarks> /// <typeparam name="T">list value type</typeparam> /// <param name="containingList">the larger list we're checking in</param> /// <param name="lookupList">the list to look for in the containing list</param> /// <returns>true if it has everything</returns> public static bool ContainsAll<T>(this IEnumerable<T> containingList, IEnumerable<T> lookupList) { return ! lookupList.Except(containingList).Any(); } 
+31
Oct 26 '12 at 17:58
source share

Included in .NET 4: Enumerable.All

 public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values) { return values.All(value => source.Contains(value)); } 
+25
Apr 26 '16 at 6:02
source share

You can also use a different method. Override peers and use this

 public bool ContainsAll(List<T> a,List<T> check) { list l = new List<T>(check); foreach(T _t in a) { if(check.Contains(t)) { check.Remove(t); if(check.Count == 0) { return true; } } return false; } } 
0
Jan 26 '14 at 18:54
source share



All Articles