
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Testing Every Element in an Array or List<T>
|
317
See Also
See the “ArrayList Class,” “Hashtable Class,” “List<T> Class,” “Dictionary<T,U>
Class,” “File Class,” and “BinaryFormatter Class” topics in the MSDN documentation.
5.15 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>( );
strings.Add("one");
strings.Add(null);
strings.Add("three");
strings.Add("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 ...