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

Kiểm tra tất cả phần tử List thỏa mãn điều kiện (Predicate) trong C#

Mục đích

Phương thức List<T>.TrueForAll(Predicate<T> match) trả về true nếu **mọi** phần tử trong list đều thỏa mãn điều kiện (predicate), ngược lại false. Dừng sớm (short-circuit) khi tìm thấy phần tử không thỏa.

Cú pháp

public bool TrueForAll(Predicate match);

Predicate<T> là delegate: bool Predicate(T obj).

Ví dụ 1: Kiểm tra tất cả số chia hết cho 10

using System;
using System.Collections.Generic;

public class Demo
{
    // Predicate: trả về true nếu số chia hết cho 10
    private static bool IsMultipleOf10(int i) => i % 10 == 0;

    public static void Main(string[] args)
    {
        List list = new List { 200, 215, 310, 500, 600 };

        Console.WriteLine("List elements:");
        foreach (int i in list) Console.WriteLine(i);

        bool allMatch = list.TrueForAll(IsMultipleOf10);
        Console.WriteLine($"\nTất cả chia hết cho 10? {allMatch}"); // False (215 không chia hết)
    }
}

Kết quả

List elements:
200
215
310
500
600

Tất cả chia hết cho 10? False

Ví dụ 2: Tất cả đều chia hết cho 10

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool IsMultipleOf10(int i) => i % 10 == 0;

    public static void Main(string[] args)
    {
        List list = new List { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };

        Console.WriteLine("List elements:");
        foreach (int i in list) Console.WriteLine(i);

        bool allMatch = list.TrueForAll(IsMultipleOf10);
        Console.WriteLine($"\nTất cả chia hết cho 10? {allMatch}"); // True
    }
}

Kết quả

List elements:
100
200
300
400
500
600
700
800
900
1000

Tất cả chia hết cho 10? True

Ví dụ 3: Dùng Lambda Expression (ngắn gọn)

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        List names = new List { "Alice", "Bob", "Charlie", "David" };

        // Kiểm tra tất cả tên có độ dài > 3
        bool allLong = names.TrueForAll(name => name.Length > 3);
        Console.WriteLine($"Tất cả tên dài > 3 ký tự? {allLong}"); // True

        // Kiểm tra tất cả tên bắt đầu bằng 'A'
        bool allStartWithA = names.TrueForAll(name => name.StartsWith("A"));
        Console.WriteLine($"Tất cả tên bắt đầu bằng 'A'? {allStartWithA}"); // False
    }
}

So sánh với LINQ All()

// TrueForAll (List method) - nhanh hơn chút, không allocate delegate nếu dùng method group
bool result1 = list.TrueForAll(IsMultipleOf10);

// LINQ All() - làm việc với bất kỳ IEnumerable, linh hoạt hơn
bool result2 = list.All(IsMultipleOf10);
bool result3 = list.All(x => x % 10 == 0);
Đặc điểmTrueForAllLINQ All()
NamespaceSystem.Collections.GenericSystem.Linq
Đối tượngChỉ List<T>Bất kỳ IEnumerable<T>
Hiệu năngHơi nhanh hơn (direct call)Giống nhau mostly
Short-circuitCóCó

Lưu ý

  • Trả về true cho list rỗng (vacuous truth).
  • Predicate không được null (ném ArgumentNullException).
  • Không sửa đổi list bên trong predicate.