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

การค้นหา Index ของ Object ใน Collection ใน C#

การค้นหา Index ใน Collection (StringCollection)

StringCollection (ใน System.Collections.Specialized) เป็นคอลเลกชันสำหรับ String มีเมธอด IndexOf() ค้นหา Index ของ Object

ตัวอย่างที่ 1: StringCollection พื้นฐาน


using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection strCol = new StringCollection();
        strCol.Add("Accessories");
        strCol.Add("Books");
        strCol.Add("Electronics");
        strCol.Add("Books");  // Duplicate
        
        Console.WriteLine("StringCollection elements...");
        foreach (string item in strCol)
        {
            Console.WriteLine(item);
        }
        
        // Insert ที่ Index 2
        strCol.Insert(2, "Headphone");
        
        Console.WriteLine("\nStringCollection elements...UPDATED");
        foreach (string item in strCol)
        {
            Console.WriteLine(item);
        }
        
        // ค้นหา Index ของ "Electronics"
        int index = strCol.IndexOf("Electronics");
        Console.WriteLine($"\nIndex of 'Electronics': {index}");  // 3 (0-based)
    }
}

ผลลัพธ์:

StringCollection elements...
Accessories
Books
Electronics
Books

StringCollection elements...UPDATED
Accessories
Books
Headphone
Electronics
Books

Index of 'Electronics': 3

ตัวอย่างที่ 2: เพิ่มจาก Array และค้นหา


using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        StringCollection stringCol = new StringCollection();
        String[] arr = new String[] { "100", "200", "300", "400", "500" };
        
        Console.WriteLine("Array elements...");
        foreach (string item in arr) Console.WriteLine(item);
        
        stringCol.AddRange(arr);
        
        Console.WriteLine($"\nContains '800'? {stringCol.Contains("800")}");  // False
        Console.WriteLine($"Count: {stringCol.Count}");  // 5
        
        // Iterate ด้วย Enumerator
        StringEnumerator enumerator = stringCol.GetEnumerator();
        while (enumerator.MoveNext())
        {
            Console.WriteLine(enumerator.Current);
        }
        
        // ค้นหา Index
        Console.WriteLine($"\nIndex of '500': {stringCol.IndexOf("500")}");  // 4
        Console.WriteLine($"Index of '1000': {stringCol.IndexOf("1000")}");  // -1 (ไม่พบ)
    }
}

ผลลัพธ์:

Array elements...
100
200
300
400
500

Contains '800'? False
Count: 5
100
200
300
400
500

Index of '500': 4
Index of '1000': -1

IndexOf() Behavior

  • คืนค่า Zero-based Index (0, 1, 2, ...)
  • คืนค่า -1 ถ้าไม่พบ
  • คืนค่า Index แรกที่พบ (First Occurrence)
  • ใช้ Equals() สำหรับการเปรียบเทียบ

List<T> - Generic Version (แนะนำ)


using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List list = new List { "A", "B", "C", "B", "D" };
        
        // IndexOf - หา Index แรก
        int index1 = list.IndexOf("B");
        Console.WriteLine($"IndexOf('B'): {index1}");  // 1
        
        // IndexOf overload: เริ่มหาจาก Index ที่ระบุ
        int index2 = list.IndexOf("B", 2);  // เริ่มจาก Index 2
        Console.WriteLine($"IndexOf('B', 2): {index2}");  // 3
        
        // IndexOf overload: เริ่มจาก Index, จำนวน Count
        int index3 = list.IndexOf("B", 2, 2);  // Index 2-3
        Console.WriteLine($"IndexOf('B', 2, 2): {index3}");  // 3
        
        // LastIndexOf - หา Index สุดท้าย
        int lastIndex = list.LastIndexOf("B");
        Console.WriteLine($"LastIndexOf('B'): {lastIndex}");  // 3
        
        // FindIndex - ใช้ Predicate (Lambda)
        int findIndex = list.FindIndex(s => s.StartsWith("C"));
        Console.WriteLine($"FindIndex(StartsWith C): {findIndex}");  // 2
        
        // FindLastIndex
        int findLast = list.FindLastIndex(s => s == "B");
        Console.WriteLine($"FindLastIndex(B): {findLast}");  // 3
    }
}

Array - ใช้ Array.IndexOf()


using System;

class Program
{
    static void Main()
    {
        string[] array = { "A", "B", "C", "B", "D" };
        
        int index = Array.IndexOf(array, "B");
        Console.WriteLine($"Array.IndexOf('B'): {index}");  // 1
        
        int lastIndex = Array.LastIndexOf(array, "B");
        Console.WriteLine($"Array.LastIndexOf('B'): {lastIndex}");  // 3
        
        // Overload: เริ่มจาก Index, Count
        int index2 = Array.IndexOf(array, "B", 2);
        Console.WriteLine($"Array.IndexOf('B', 2): {index2}");  // 3
    }
}

Dictionary / HashSet - ไม่มี Index

Dictionary และ HashSet เป็น Unordered (ไม่มี Index) ใช้ Key/Hash แทน


var dict = new Dictionary { { "A", 1 }, { "B", 2 } };
// dict.IndexOf(...) ❌ ไม่มี

// แต่สามารถหา Key ได้
bool hasKey = dict.ContainsKey("A");  // True
int value = dict["A"];  // 1

สรุปเมธอดค้นหา Index

CollectionMethodคืนค่า
StringCollectionIndexOf(value)int (-1 ถ้าไม่พบ)
List<T>IndexOf, LastIndexOf, FindIndex, FindLastIndexint (-1 ถ้าไม่พบ)
ArrayArray.IndexOf, Array.LastIndexOfint (-1 ถ้าไม่พบ)
ArrayListIndexOf, LastIndexOfint (-1 ถ้าไม่พบ)

Key Points

  • IndexOf = First Occurrence, LastIndexOf = Last Occurrence
  • คืนค่า -1 ถ้าไม่พบ (ไม่ใช่ Exception)
  • List<T> มี Overload มากกว่า: StartIndex, Count, Predicate (FindIndex)
  • Generic List<T> แนะนำกว่า StringCollection / ArrayList (Type Safety, Performance)