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

Phương thức Array.Find() trong C#

Phương thức Array.Find() trong C# được dùng để tìm kiếm phần tử khớp với điều kiện được định nghĩa bởi predicate và trả về lần xuất hiện đầu tiên trong toàn bộ mảng.

Cú pháp

Cú pháp như sau:

public static T Find(T[] array, Predicate match);

Tham số array là mảng một chiều, zero-based để tìm kiếm, match là predicate định nghĩa điều kiện tìm kiếm.

Ví dụ - Tìm phần tử bắt đầu bằng 't'

using System;

public class Demo
{
    public static void Main()
    {
        Console.WriteLine("Array elements...");
        string[] arr = { "car", "bike", "truck", "bus" };
        for (int i = 0; i < arr.Length; i++)
        {
            Console.Write("{0} ", arr[i]);
        }
        Console.WriteLine();

        string res = Array.Find(arr, ele => ele.StartsWith("t", StringComparison.Ordinal));
        Console.Write("Searched element...");
        Console.Write("{0}", res);
    }
}

Kết quả

Array elements... car bike truck bus
Searched element...truck