Recipe 5.15. Testing Every Element in an Array or List<T>ProblemYou 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. SolutionUse 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); DiscussionThe 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…
…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 AlsoSee the "Array Class," "List<T> Class," and "TrueForAll Method" topics in the MSDN documentation. |