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

การดึงข้อมูลจาก Collection ใน C#

การเข้าถึงข้อมูลใน List Collection

List<T> รองรับการเข้าถึงแบบ Index-Based (เช่น Array) และการวนลูปด้วย foreach

วิธีการเข้าถึงข้อมูล

1. Indexer (Index-Based Access)

List list = new List { 20, 40, 60, 80 };

int first = list[0];    // 20 - สมาชิกแรก (Index 0)
int second = list[1];   // 40
int last = list[list.Count - 1]; // 80 - สมาชิกสุดท้าย

// ⚠️ IndexOutOfRangeException ถ้า Index เกินขอบเขต
// int error = list[10]; // Crash!

2. foreach Loop (Sequential Access)

foreach (int val in list) {
    Console.WriteLine(val);
}
// Output: 20, 40, 60, 80

3. for Loop ด้วย Index

for (int i = 0; i < list.Count; i++) {
    Console.WriteLine($"Index {i}: {list[i]}");
}

4. LINQ Methods

// First / Last
int first = list.First();
int last = list.Last();

// With Condition
int firstEven = list.First(x => x % 2 == 0);
int lastEven = list.Last(x => x % 2 == 0);

// Safe Versions (ไม่ Throw Exception ถ้าไม่เจอ)
int? firstOrDefault = list.FirstOrDefault(x => x > 100); // null
int? singleOrDefault = list.SingleOrDefault(x => x == 40); // 40

โค้ดตัวอย่างสมบูรณ์

using System;
using System.Collections.Generic;
using System.Linq;

class Demo {
    static void Main(String[] args) {
        List list = new List();
        list.Add(20);
        list.Add(40);
        list.Add(60);
        list.Add(80);
        
        Console.WriteLine("=== วนลูปด้วย foreach ===");
        foreach (int val in list) {
            Console.WriteLine(val);
        }
        
        Console.WriteLine("\n=== เข้าถึงด้วย Index ===");
        int a = list[0];
        Console.WriteLine("First element: " + a);
        Console.WriteLine("Second element: " + list[1]);
        Console.WriteLine("Last element: " + list[list.Count - 1]);
        
        Console.WriteLine("\n=== LINQ Methods ===");
        Console.WriteLine("First: " + list.First());
        Console.WriteLine("Last: " + list.Last());
        Console.WriteLine("Element at index 2: " + list.ElementAt(2));
        
        // Safe Access
        Console.WriteLine("\n=== Safe Access ===");
        Console.WriteLine("ElementAtOrDefault(10): " + list.ElementAtOrDefault(10)); // 0
        Console.WriteLine("FirstOrDefault(x > 100): " + list.FirstOrDefault(x => x > 100)); // 0
    }
}

ตัวอย่างผลลัพธ์

=== วนลูปด้วย foreach ===
20
40
60
80

=== เข้าถึงด้วย Index ===
First element: 20
Second element: 40
Last element: 80

=== LINQ Methods ===
First: 20
Last: 80
Element at index 2: 60

=== Safe Access ===
ElementAtOrDefault(10): 0
FirstOrDefault(x > 100): 0

Best Practices

  • ใช้ foreach สำหรับการอ่านแบบ Sequential (อ่านง่าย ปลอดภัย)
  • ใช้ Indexer [i] เมื่อต้องการ Random Access หรือต้องการ Index
  • ใช้ FirstOrDefault/LastOrDefault แทน First/Last เพื่อป้องกัน Exception
  • ใช้ ElementAtOrDefault แทน Indexer ถ้า Index อาจเกินขอบเขต
  • หลีกเลี่ยงการ Modify Collection ขณะกำลัง Iterate (ใช้ ToList() ก่อน)

การเข้าถึง Collection อื่นๆ

Collection Index Access Key Access Enumeration
List<T> ✅ [index] ❌ ✅ foreach
Array ✅ [index] ❌ ✅ foreach
Dictionary<K,V> ❌ ✅ [key] ✅ foreach (KeyValuePair)
HashSet<T> ❌ ❌ ✅ foreach
Queue<T> ❌ ❌ ✅ (Dequeue)
Stack<T> ❌ ❌ ✅ (Pop)