5.12. Testing Every Element in an Array or List<T>
Problem
You need an easy way to test every element in an Array or List<T>. The results of this test should indicate that the test passed for all elements in the collection, or it failed for at least one element in the collection.
Solution
Use the TrueForAll method, as shown here:
// Create a List of strings.
List<string> strings = new List<string>() {"one",null,"three","four"};
// Determine if there are no null values in the List.
string str = strings.TrueForAll(delegate(string val)
{
if (val == null)
return false;
else
return true;
}).ToString();
// Display the results.
Console.WriteLine(str);Discussion
The addition of the TrueForAll method on the Array and List<T> classes allows you to easily set up tests for all elements in these collections. The code in the Solution for this recipe tests all elements to determine if any are null. You could just as easily set up tests to determine…
If any numeric elements are above a specified maximum value
If any numeric elements are below a specified minimum value
If any string elements contain a specified set of characters
If any data objects have all of their fields filled in
…as well as any others you may come up with.
The TrueForAll method accepts a generic delegate Predicate<T> called match and returns a Boolean value:
public bool TrueForAll(Predicate<T> match)
The match parameter determines whether or not a true or false should be returned by the TrueForAll method.
The TrueForAll method basically ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access