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ểm | Array.TrueForAll | LINQ All() |
|---|---|---|
| Namespace | System | System.Linq |
| Đối tượng | Chỉ mảng (T[]) | Mọi IEnumerable<T> |
| Hiệu suất | Hơi nhanh hơn (tránh delegate overhead) | Chuẩn LINQ |
| Short-circuit | Có | 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
ArgumentNullExceptionnếu array hoặc predicate là null. - Có thể dùng method group:
Array.TrueForAll(val, IsPositive)vớistatic bool IsPositive(int x) => x > 0;.