List<T>.TrueForAll(Predicate<T>) is used to check whether every element in the List<T> matches the conditions defined by the specified predicate or not. Syntax:
public bool TrueForAll (Predicate<T> match);
Parameter:
match: It is the Predicate<T> delegate which defines the conditions to check against the elements.
Return Value: This method returns true if every element in the List<T> matches the conditions defined by the specified predicate otherwise it returns false. If the list has no elements, the return value is true. Exception: This method will give ArgumentNullException if the match is null. Below programs illustrate the use of List<T>.TrueForAll(Predicate<T>) Method: Example 1:
// C# Program to check if every element // in the List matches the conditions // defined by the specified predicate using System;
using System.Collections;
using System.Collections.Generic;
class Geeks {
// function which checks whether an
// element is even or not. Or you can
// say it is the specified condition
private static bool isEven( int i)
{
return ((i % 2) == 0);
}
// Main Method
public static void Main(String[] args)
{
// Creating a List<T> of Integers
List< int > firstlist = new List< int >();
// Adding elements to List
for ( int i = 0; i <= 10; i+=2) {
firstlist.Add(i);
}
Console.WriteLine("Elements Present in List:\n");
// Displaying the elements of List
foreach ( int k in firstlist)
{
Console.WriteLine(k);
}
Console.WriteLine(" ");
Console.Write("Result: ");
// Checks if all the elements of firstlist
// matches the condition defined by predicate
Console.WriteLine(firstlist.TrueForAll(isEven));
}
} |
Elements Present in List: 0 2 4 6 8 10 Result: True
Example 2:
// C# Program to check if every element //in the List matches the conditions //defined by the specified predicate using System;
using System.Collections;
using System.Collections.Generic;
public class Example
{ public static void Main()
{
List< string > lang = new List< string >();
lang.Add("C# language");
lang.Add("C++ language");
lang.Add("Java language");
lang.Add("Python language");
lang.Add("Ruby language");
Console.WriteLine("Elements Present in List:\n");
foreach ( string language in lang)
{
Console.WriteLine(language);
}
Console.WriteLine(" ");
Console.Write("TrueForAll(EndsWithLanguage): ");
// Checks if all the elements of lang
// matches the condition defined by predicate
Console.WriteLine(lang.TrueForAll(EndsWithLanguage));
}
// Search predicate returns
// true if a string ends in "language".
private static bool EndsWithLanguage(String s)
{
return s.ToLower().EndsWith("language");
}
} |
Elements Present in List: C# language C++ language Java language Python language Ruby language TrueForAll(EndsWithLanguage): True
Reference: