Recipe5.15.Testing Every Element in an Array or ListT


Recipe 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 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 consists of a loop that iterates over each element in the collection. Within this loop, a call to the match delegate is invoked. If this delegate returns true, the processing continues on to the next element in the collection. If this delegate returns false, processing stops and a false is returned by the trueForAll method. When the trueForAll method is finished iterating over all the elements of the collection and the match delegate has not returned a false value for any element, the trueForAll method returns a true.

See Also

See the "Array Class," "List<T> Class," and "TrueForAll Method" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net