C# 数组 - TrueForAll() 方法

C# 数组 TrueForAll() 方法用于判断数组中的所有元素是否都符合指定谓词定义的条件。如果数组中的每个元素都符合指定谓词定义的条件,则返回 true;否则,返回 false

如果数组中没有元素,则此函数返回 true

语法

以下是 C# 数组 TrueForAll() 方法的语法 -

public static bool TrueForAll<T> (T[] array, Predicate<T> match);

参数

此方法接受以下参数 -

  • array:用于检查条件的一维数组。
  • match:用于定义检查元素条件的谓词。

返回值

此方法返回布尔值。如果每个元素都符合指定的谓词,则返回 True;否则返回 false。

示例 1:检查正整数

让我们创建一个 TrueForAll() 方法的基本示例,以检查数组中的每个元素是否为正 -

using System;
public class Example {
   public static void Main() {
      // 整数数组
      int[] numbers = { 5, 10, 15, 20, 25 };

      // 使用 Array.TrueForAll 检查所有元素是否为正
      bool allPositive = Array.TrueForAll(numbers, IsPositive);

      if (allPositive)
         Console.WriteLine("All elements in the array are positive.");
      else
         Console.WriteLine("Not all elements in the array are positive.");
   }
   public static bool IsPositive(int number) {
      return number > 0;
   }
}

输出

以下是输出 -

All elements in the array are positive.

示例 2:检查每个元素是否以整数结尾

让我们看另一个使用 TrueForAll() 方法的示例,以检查每个元素是否以整数结尾 -

using System;
public class Example {
   public static void Main() {
      String[] values = { "Y2K", "A2000", "DC2A6", "MMXIV", "0C3" };

      if (Array.TrueForAll(values, EndsWithANumber))
         Console.WriteLine("All elements end with an integer.");
      else
         Console.WriteLine("Not all elements end with an integer.");
   }

   private static bool EndsWithANumber(string value){
      int s;
      return int.TryParse(value.Substring(value.Length - 1), out s);
   }
}

输出

以下是输出 -

Not all elements end with an integer.

示例 3:以 X 结尾的字符串

这是 TrueForAll() 方法的另一个示例。在这里,我们使用此方法检查每个元素是否都以 x 结尾 -

using System;

public class Example {
   public static void Main() {
      // 字符串数组
      string[] words = { "Box", "Fox", "Mix", "Six" };

      // 检查所有单词是否以"X"结尾
      bool allEndWithX = Array.TrueForAll(words, EndsWithX);

      if (allEndWithX)
         Console.WriteLine("All words in the array end with 'X'.");
      else
         Console.WriteLine("Not all words in the array end with 'X'.");
   }

   // 谓词方法检查字符串是否以"X"结尾
   public static bool EndsWithX(string word) {
      if (string.IsNullOrEmpty(word))
         return false;

      return word.EndsWith("X", StringComparison.OrdinalIgnoreCase);
   }
}

输出

以下是输出 -

All words in the array end with 'X'.

示例 4:检查所有元素是否为偶数

在此示例中,我们使用 TrueForAll() 方法检查数组中的每个元素是否为偶数 -

using System;
public class Example {
   public static void Main() {
      // 整数数组
      int[] numbers = { 2, 4, 6, 8, 10 };

      // 检查所有元素是否都是偶数
      bool allEven = Array.TrueForAll(numbers, IsEven);

      if (allEven)
         Console.WriteLine("All elements in the array are even numbers.");
      else
         Console.WriteLine("Not all elements in the array are even numbers.");
   }

   // 谓词方法检查数字是否为偶数
   public static bool IsEven(int number) {
      return number % 2 == 0;
      return number % 2 == 0;
   }
}

输出

以下是输出 -

All elements in the array are even numbers.

csharp_array_class.html