C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument 1: This is the array that we are testing. In this program, this is the array of 4 integers called "values."
Argument 2: This is a predicate lambda. The predicate method returns true whenever a number is not evenly divisible by two.
Odd, EvenLambda: We specify the second argument with lambda expression syntax, which is a shorter way of writing a method.
LambdaC# program that uses Array.TrueForAll
using System;
class Program
{
static void Main()
{
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);
}
}
Output
TRUEFORALL: True
Info: We see that Array.TrueForAll correctly applies the predicate to every element in the array.
C# program that uses TrueForAll, false result
using System;
class Program
{
static void Main()
{
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);
}
}
Output
RESULT: False
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.