Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ค้นหา Index สุดท้ายที่ Match เงื่อนไขใน List C# (FindLastIndex)

List.FindLastIndex Method

ค้นหา Element ที่ Match Predicate จากท้ายมาหน้า คืนค่า Zero-based Index (หาไม่เจอ = -1)

Overloads


// 1. Search ทั้ง List
int FindLastIndex(Predicate match)

// 2. Search จาก Index ถึงต้น
int FindLastIndex(int startIndex, Predicate match)

// 3. Search ใน Range
int FindLastIndex(int startIndex, int count, Predicate match)

ตัวอย่างพื้นฐาน


using System;
using System.Collections.Generic;

public class Demo
{
    // Predicate: หาร 10 ลงตัว
    private static bool DivisibleBy10(int i) => (i % 10) == 0;
    
    public static void Main()
    {
        List list = new List { 200, 215, 310, 500, 600 };
        
        Console.WriteLine("List: " + string.Join(", ", list));
        
        // หา Index สุดท้ายที่หาร 10 ลงตัว
        int lastIndex = list.FindLastIndex(DivisibleBy10);
        
        Console.WriteLine($"Last Index (Divisible by 10): {lastIndex}");
        // Output: 4 (600 อยู่ Index 4)
        
        // Lambda Expression
        int lastEven = list.FindLastIndex(x => x % 2 == 0);
        Console.WriteLine($"Last Even Index: {lastEven}"); // 4 (600)
        
        // หาไม่เจอ
        int notFound = list.FindLastIndex(x => x > 1000);
        Console.WriteLine($"Not Found: {notFound}"); // -1
    }
}

Output

List: 200, 215, 310, 500, 600
Last Index (Divisible by 10): 4
Last Even Index: 4
Not Found: -1

ตัวอย่างที่ 2: เริ่มค้นหาจากตำแหน่งเฉพาะ


List numbers = new List { 10, 20, 30, 40, 50, 60, 70 };

// ค้นหาจาก Index 3 (Value 40) ถึงต้น
int index = numbers.FindLastIndex(3, x => x % 20 == 0);
Console.WriteLine($"From index 3 backward: {index}"); // 2 (Value 30)

// ค้นหา 3 Elements จาก Index 5 ถึงต้น (Indices 5,4,3)
int index2 = numbers.FindLastIndex(5, 3, x => x > 35);
Console.WriteLine($"Range 5,3: {index2}"); // 5 (Value 60)

Related Methods

MethodคำอธิบายReturn
FindIndexหา Index แรกที่ Match (จากหน้า)int (-1 if not found)
FindLastIndexหา Index สุดท้ายที่ Match (จากหลัง)int (-1 if not found)
Findหา Element แรกที่ MatchT (default if not found)
FindLastหา Element สุดท้ายที่ MatchT (default if not found)
FindAllหา Elements ทั้งหมดที่ MatchList<T>
Existsเช็คว่ามี Match หรือไม่bool
TrueForAllเช็คว่าทุก Element Matchbool

Predicate Delegate


// Predicate = Func
// 3 รูปแบบการเขียน

// 1. Method Group
bool IsEven(int x) => x % 2 == 0;
int idx1 = list.FindLastIndex(IsEven);

// 2. Lambda Expression
int idx2 = list.FindLastIndex(x => x % 2 == 0);

// 3. Anonymous Method (Old Style)
int idx3 = list.FindLastIndex(delegate(int x) { return x % 2 == 0; });

Performance & Alternatives

  • O(n) Linear Search จากท้าย
  • Sorted List → ใช้ Binary Search (BinarySearch) O(log n)
  • Frequent Search → ใช้ Dictionary/HashSet O(1)
  • LINQ: list.Select((v,i) => new {v,i}).LastOrDefault(x => x.v % 10 == 0)?.i ?? -1

Best Practice

  • ✅ ใช้ Lambda สำหรับ Simple Predicates
  • ✅ Extract Method สำหรับ Complex Logic (Reusable, Testable)
  • ✅ Check Return Value -1 ก่อนใช้เป็น Index
  • ❌ หลีกเลี่ยง Side Effects ใน Predicate