ภาพรวม
เมธอด Array.LastIndexOf() ใช้ค้นหา ดัชนีสุดท้าย (last index) ของค่าที่ระบุในอาร์เรย์ คืนค่า -1 หากไม่พบ
รูปแบบการใช้งาน
int[] val = { 97, 45, 76, 21, 89, 45 };
int lastIndex = Array.LastIndexOf(val, 45); // 5 (ดัชนีของ 45 ตัวที่สอง)
ตัวอย่างโค้ดเต็ม
using System;
public class Demo
{
public static void Main()
{
int[] val = { 97, 45, 76, 21, 89, 45 };
int res = Array.LastIndexOf(val, 45);
Console.WriteLine("Index of element 45 is = " + res);
}
}
ผลลัพธ์
Index of element 45 is = 5
เมธอดค้นหาที่เกี่ยวข้อง
| เมธอด | คำอธิบาย | คืนค่าเมื่อไม่พบ |
|---|---|---|
IndexOf | ดัชนีแรกที่พบ (ค้นจากหน้า) | -1 |
LastIndexOf | ดัชนีสุดท้ายที่พบ (ค้นจากหลัง) | -1 |
BinarySearch | ค้นหาแบบทวิภาค (ต้องจัดเรียง) | ~index (bitwise complement) |
FindLastIndex (List) | ดัชนีสุดท้ายที่ตรง predicate | -1 |