Does .NET Have an Inbuilt Function to Check if List a Contains All Items in List b?
The purpose of this question is to determine if .NET provides an inbuilt functionality to ascertain whether one list contains all the elements of another list.
The provided sample code attempts to fulfill this purpose by iterating through the second list and checking if each element is present in the first list. This approach works, but one wonders if such functionality already exists within .NET.
Answer:
For .NET version 3.5 and above, such a function is indeed available:
public static bool ContainsAllItems<T>(List<T> a, List<T> b) { return !b.Except(a).Any(); }
This code compares the elements in list b with those in list a, returning true only if all elements in b are also present in a.
Alternative Implementation:
A more conventional implementation would involve declaring the method as generic and accepting an IEnumerable
public static class LinqExtras { public static bool ContainsAllItems<T>(this IEnumerable<T> a, IEnumerable<T> b) { return !b.Except(a).Any(); } }
Using this approach, you can easily check if one list contains all the elements of another using:
IEnumerable<int> a = new List<int> { 1, 2, 3, 4 }; IEnumerable<int> b = new List<int> { 2, 4, 6, 8 }; bool containsAll = a.ContainsAllItems(b); // False
The above is the detailed content of Does .NET Offer a Built-in Function to Check if One List Contains All Items from Another?. For more information, please follow other related articles on the PHP Chinese website!