📌  相关文章
📜  C#|检查每个List元素是否匹配谓词条件

📅  最后修改于: 2021-05-29 22:35:32             🧑  作者: Mango

List .TrueForAll(Predicate )用于检查List 中的每个元素是否与指定谓词定义的条件匹配。

句法:

public bool TrueForAll (Predicate match);

范围:

返回值:如果List 中的每个元素都匹配指定谓词定义的条件,则此方法返回true ,否则返回false 。如果列表中没有元素,则返回值为true

异常:如果匹配为null,则此方法将提供ArgumentNullException。

下面的程序说明了List .TrueForAll(Predicate )方法的用法:

范例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