ภาพรวม
ใช้ List<T>.FindIndex พร้อม Lambda expression เพื่อหาดัชนีของ item ที่ตรงเงื่อนไขในบรรทัดเดียว
โค้ดตัวอย่าง
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List<string> myList = new List<string> { "Football", "Soccer", "Tennis" };
// หา index ของ item ที่มีค่า "Tennis"
int index = myList.FindIndex(item => item == "Tennis");
Console.WriteLine($"List Item 'Tennis' found at index: {index}");
// Output: 2
// หา index ของ item ที่ Contains "ball"
int index2 = myList.FindIndex(item => item.Contains("ball"));
Console.WriteLine($"First item containing 'ball': index {index2}");
// Output: 0 (Football)
// ไม่พบ = -1
int notFound = myList.FindIndex(item => item == "Golf");
Console.WriteLine($"Golf index: {notFound}"); // -1
}
}
ผลลัพธ์
List Item 'Tennis' found at index: 2
First item containing 'ball': index 0
Golf index: -1
เมธอดที่เกี่ยวข้อง
| Method | คืนค่า | คำอธิบาย |
|---|---|---|
FindIndex(Predicate<T>) | int | Index แรกที่ match (หรือ -1) |
FindLastIndex(Predicate<T>) | int | Index สุดท้ายที่ match |
Find(Predicate<T>) | T | Element แรกที่ match (หรือ default) |
FindAll(Predicate<T>) | List<T> | Elements ทั้งหมดที่ match |
Exists(Predicate<T>) | bool | มี item match หรือไม่ |
IndexOf(T) | int | Index ของค่าที่กำหนด (equality) |
LastIndexOf(T) | int | Index สุดท้ายของค่าที่กำหนด |
Predicate Delegate
Predicate<T> คือ `Func<T, bool>` - ฟังก์ชันรับ T คืน bool
// รูปแบบต่างๆ
list.FindIndex(x => x == "Tennis"); // Lambda
list.FindIndex(IsTennis); // Method group
list.FindIndex(delegate(string s) { return s == "Tennis"; }); // Anonymous method
bool IsTennis(string s) => s == "Tennis";
หมายเหตุ
- คืนค่า -1 ถ้าไม่พบ (ไม่ได้ throw exception)
- ค้นหาแบบ Linear search O(n)
- สำหรับ Array ใช้
Array.FindIndexหรือArray.IndexOf