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

Tìm index phần tử trong List C# một bước

Dùng List<T>.FindIndex với predicate lambda để tìm index phần tử thỏa mãn điều kiện trong một dòng code.

Ví dụ minh họa

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var sports = new List { "Football", "Soccer", "Tennis", "Badminton" };
        
        // Tìm index phần tử chứa "Tennis"
        int index = sports.FindIndex(s => s.Contains("Tennis"));
        Console.WriteLine($"Index của 'Tennis': {index}"); // 2
        
        // Tìm index phần tử bắt đầu bằng 'B'
        int indexB = sports.FindIndex(s => s.StartsWith("B"));
        Console.WriteLine($"Index bắt đầu bằng 'B': {indexB}"); // 3
        
        // Không tìm thấy → trả về -1
        int notFound = sports.FindIndex(s => s.Contains("Golf"));
        Console.WriteLine($"Không tìm thấy: {notFound}"); // -1
        
        // FindLastIndex - tìm từ cuối về đầu
        var dupList = new List { "A", "B", "A", "C" };
        Console.WriteLine($"FindIndex('A'): {dupList.FindIndex(s => s == "A")}"); // 0
        Console.WriteLine($"FindLastIndex('A'): {dupList.FindLastIndex(s => s == "A")}"); // 2
    }
}

Kết quả đầu ra

Index của 'Tennis': 2
Index bắt đầu bằng 'B': 3
Không tìm thấy: -1
FindIndex('A'): 0
FindLastIndex('A'): 2

Phương thức liên quan: Find (trả về phần tử), FindAll (trả về list), FindLast, Exists (bool), TrueForAll (bool).