C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
First: The Predicate variables are assigned to lambda expressions. At this point they are valid predicates.
Then: The program demonstrates how the Invoke method always returns true or false when it is called.
Syntax: The => syntax separates the arguments from the method bodies. The right-hand side is evaluated to a Boolean result.
Note: The two above lambdas return true if the argument is one, and if the argument is greater than four.
C# program that uses Predicate type instances
using System;
class Program
{
static void Main()
{
//
// This Predicate instance returns true if the argument is one.
//
Predicate<int> isOne =
x => x == 1;
//
// This Predicate returns true if the argument is greater than 4.
//
Predicate<int> isGreaterEqualFive =
(int x) => x >= 5;
//
// Test the Predicate instances with various parameters.
//
Console.WriteLine(isOne.Invoke(1));
Console.WriteLine(isOne.Invoke(2));
Console.WriteLine(isGreaterEqualFive.Invoke(3));
Console.WriteLine(isGreaterEqualFive.Invoke(10));
}
}
Output
True
False
False
True
Here: We create a string array of 3 elements. Each string in the array has at least 4 characters.
TrueForAll: We pass a lambda expression to TrueForAll, which receives a Predicate instance. The return value is a bool.
Result: The Predicate returns true if the string has 3 or more chars. This is true for all items in the array, so TrueForAll returns true.
C# program that uses Predicate, List method
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var items = new List<string> { "compiler", "interpreter", "file" };
// Use TrueForAll with a predicate.
if (items.TrueForAll(item => item.Length >= 3))
{
Console.WriteLine("PREDICATE TrueForAll");
}
}
}
Output
PREDICATE TrueForAll
Note: The type Predicate in the .NET Framework adheres to this definition. It is a specific implementation of the concept.