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.
Notes, method. 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.
First example. 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
Example, false. Here the numbers in the array are not all odd. Therefore the same Array.TrueForAll parameters will have the method return false.
Info We see that 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
Discussion. 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.
Info Typically, this sort of approach is much faster than using a call such as Array.TrueForAll.
However Array.TrueForAll is less familiar to programmers used to other languages. Its use might make a development team less efficient.
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 20, 2023 (edit).