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

Tìm phần tử đầu tiên thỏa mãn điều kiện trong List (Find) trong C#

Mục đích

Phương thức List<T>.Find(Predicate<T> match) trả về **phần tử đầu tiên** thỏa mãn điều kiện match. Trả về default(T) (null cho reference type, 0 cho int...) nếu không tìm thấy.

Ví dụ 1: Tìm số chia hết cho 10 đầu tiên

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 { 200, 215, 310, 500, 600 };

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

        int first = list.Find(IsMultipleOf10);
        Console.WriteLine($"\nFirst occurrence (chia hết 10): {first}"); // 200
    }
}

Kết quả

List:
200
215
310
500
600

First occurrence (chia hết 10): 200

Ví dụ 2: Tìm số chẵn đầu tiên

using System;
using System.Collections.Generic;

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

    public static void Main(string[] args)
    {
        List list = new List { 255, 315, 410, 500, 600, 710, 800, 1000 };

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

        int first = list.Find(IsEven);
        Console.WriteLine($"\nFirst even: {first}"); // 410
    }
}

Kết quả

List:
255
315
410
500
600
710
800
1000

First even: 410

Các phương thức tìm kiếm liên quan

Phương thứcMô tảTrả về
Find(Predicate)Phần tử đầu tiên khớpT (hoặc default)
FindLast(Predicate)Phần tử cuối cùng khớpT (hoặc default)
FindIndex(Predicate)Index phần tử đầu khớpint (-1 nếu không)
FindLastIndex(Predicate)Index phần tử cuối khớpint (-1 nếu không)
FindAll(Predicate)**Tất cả** phần tử khớp (List mới)List<T>
Exists(Predicate)Có ít nhất 1 khớp?bool
TrueForAll(Predicate)Tất cả đều khớp?bool

Ví dụ: FindAll, FindIndex


List nums = new List { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var evens = nums.FindAll(x => x % 2 == 0);        // [2,4,6,8,10]
int firstEvenIdx = nums.FindIndex(x => x % 2 == 0); // 1
int lastEvenIdx = nums.FindLastIndex(x => x % 2 == 0); // 9
int firstEven = nums.Find(x => x % 2 == 0);       // 2
int lastEven = nums.FindLast(x => x % 2 == 0);    // 10
bool hasEven = nums.Exists(x => x % 2 == 0);      // true
bool allEven = nums.TrueForAll(x => x % 2 == 0);  // false

Predicate là gì?

Delegate: public delegate bool Predicate<in T>(T obj);. Có thể dùng:

  • Method group: list.Find(IsEven)
  • Lambda: list.Find(x => x > 5)
  • Anonymous method: list.Find(delegate(int x) { return x > 5; })

Lưu ý

  • Duyệt từ đầu (index 0) -> O(n) worst case.
  • Trả về default(T) nếu không tìm thấy. Với int -> 0. Cần kiểm tra Exists trước nếu 0 là giá trị hợp lệ.
  • Không sửa đổi list trong predicate.