List
句法:
public bool TrueForAll (Predicate match);
范围:
match: It is the Predicate
返回值:如果List
异常:如果匹配为null,则此方法将提供ArgumentNullException。
下面的程序说明了List
范例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 of Integers
List firstlist = new List();
// 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
范例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 lang = new List();
lang.Add("C# language");
lang.Add("C++ language");
lang.Add("Java language");
lang.Add("Pyhton 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
Pyhton language
Ruby language
TrueForAll(EndsWithLanguage): True
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1.trueforall?view=netframework-4.7.2