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

หา Index ของ Item ใน List แบบ Single Step ใน C#

ภาพรวม

ใช้ 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>)intIndex แรกที่ match (หรือ -1)
FindLastIndex(Predicate<T>)intIndex สุดท้ายที่ match
Find(Predicate<T>)TElement แรกที่ match (หรือ default)
FindAll(Predicate<T>)List<T>Elements ทั้งหมดที่ match
Exists(Predicate<T>)boolมี item match หรือไม่
IndexOf(T)intIndex ของค่าที่กำหนด (equality)
LastIndexOf(T)intIndex สุดท้ายของค่าที่กำหนด

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