Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức TrueForAll trong mảng C#


Giới thiệu

Phương thức tĩnh Array.TrueForAll<T>(T[] array, Predicate<T> match) kiểm tra xem tất cả phần tử trong mảng có thỏa mãn điều kiện (predicate) hay không. Trả về true nếu tất cả thỏa mãn, false nếu có ít nhất một không thỏa mãn.

Ví dụ cơ bản

int[] val = { 97, 45, 76, 21, 89, 45 };
bool result = Array.TrueForAll(val, res => res > 1); // true

Ví dụ hoàn chỉnh

using System;

public class Demo
{
    public static void Main()
    {
        int[] val = { 97, 45, 76, 21, 89, 45 };
        bool result = Array.TrueForAll(val, res => res > 1);
        Console.WriteLine(result); // True
    }
}

Kết quả

True

So sánh với LINQ All()

Đặc điểmArray.TrueForAllLINQ All()
NamespaceSystemSystem.Linq
Đối tượngChỉ mảng (T[])Mọi IEnumerable<T>
Hiệu suấtHơi nhanh hơn (tránh delegate overhead)Chuẩn LINQ
Short-circuitCóCó

Ví dụ với mảng rỗng

int[] empty = { };
bool result = Array.TrueForAll(empty, x => x > 0); // true (vacuous truth)

Lưu ý

  • Predicate là Func<T, bool> (delegate).
  • Ném ArgumentNullException nếu array hoặc predicate là null.
  • Có thể dùng method group: Array.TrueForAll(val, IsPositive) với static bool IsPositive(int x) => x > 0;.