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.
You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
Using any() along with a generator expression: list1 = ['item1','item2','item3'] list2 = ['item4','item5','item3'] if any(x in list1 for x in list2): print("Duplicates found.") else: print("No duplicates found.")
To see if one list contains the values in another use the List<t>.Intersect [ ^] method and check against the Count Any property
Example 1 – Check if Element is in C# List using Contains () In the following program, we have a list of integers. We shall check if element 68 is present in the list or not using Contains () method. As 68 is present in the list, List.Contains () method returns True.
The object to locate in the List<T>. The value can be null for reference types. true if item is found in the List<T>; otherwise, false. The following example demonstrates the Contains and Exists methods on a List<T> that contains a simple business object that implements Equals.
To check if an element is present in the list, use List.Contains () method. The definition of List.Contains () method is given below. If given element is present in the list, then List.Contains () returns True, else, it returns False.
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(); } }
Included in .NET 4: Enumerable.All
public static bool ContainsAll<T>(IEnumerable<T> source, IEnumerable<T> values) { return values.All(value => source.Contains(value)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With