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

โปรแกรม C# หาองค์ประกอบที่ตรงตามเงื่อนไขล่าสุดในอาร์เรย์


ภาพรวม

เมธอด 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