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

โปรแกรม C# หาดัชนีขององค์ประกอบใน List


ภาพรวม

เมธอด IndexOf() ของ List<T> ใช้ค้นหา ดัชนีแรก (first index) ขององค์ประกอบที่ระบุ คืนค่า -1 หากไม่พบ

รูปแบบการใช้งาน

List val = new List { 35, 55, 68 };
int index = val.IndexOf(68); // 2

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        List val = new List { 35, 55, 68 };
        int index = val.IndexOf(68);
        Console.WriteLine(index); // 2
    }
}

ผลลัพธ์

2

เมธอดที่เกี่ยวข้อง

  • LastIndexOf(item) - ค้นหาดัชนีสุดท้ายที่พบ
  • BinarySearch(item) - ค้นหาแบบทวิภาค (ต้องจัดเรียงล่วงหน้า) เร็วกว่า O(log n)
  • FindIndex(predicate) - ค้นหาดัชนีแรกที่ตรงเงื่อนไข
  • Contains(item) - ตรวจสอบมีอยู่ไหม (bool) ไม่ให้ดัชนี