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