Array.TrueForAll
This is a static
Array method. It gives you a declarative way to test every element in your array for some condition using a Predicate
.
TrueForAll
scans the array and returns true or false. The Predicate
is invoked for each element in the array. We determine whether it returns true for all elements.
We demonstrate the Array.TrueForAll
method. Our program uses an int
array of 4 odd numbers. The Array.TrueForAll
method is invoked and the predicate is specified.
using System; int[] values = { 1, 3, 5, 7 }; // See if modulo 2 is 1 for all elements. bool result = Array.TrueForAll(values, y => y % 2 == 1); Console.WriteLine("TRUEFORALL: {0}", result);TRUEFORALL: True
Here the numbers in the array are not all odd. Therefore the same Array.TrueForAll
parameters will have the method return false.
Array.TrueForAll
correctly applies the predicate to every element in the array.using System; int[] values = { 2, 5, 8 }; // Test for all odd numbers again. bool result = Array.TrueForAll(values, y => y % 2 == 1); Console.WriteLine("RESULT: {0}", result);RESULT: False
We could write a method that does the same thing as Array.TrueForAll
. This method would test each element in a foreach
-loop, and return early if an element doesn't match.
Array.TrueForAll
.Array.TrueForAll
is less familiar to programmers used to other languages. Its use might make a development team less efficient.Array.TrueForAll
can simplify some programs. By applying the predicate argument to each element, we can test every element of the array for some condition.