Dictionary<TKey, TValue> และ Array มีโครงสร้างและการใช้งานต่างกันพื้นฐาน
Dictionary<TKey, TValue>
- Key-Value Pair Collection (Hash Table)
- Key ต้อง Unique, ไม่เป็น Null (Reference Type)
- Lookup O(1) ด้วย Key
- Dynamic Size
- Namespace:
System.Collections.Generic
การประกาศและใช้งาน
using System.Collections.Generic;
var dict = new Dictionary();
dict.Add(1, 97);
dict.Add(2, 89);
dict[3] = 77; // Indexer Syntax (Add or Update)
// Access
int score = dict[1]; // 97 (Throw KeyNotFoundException ถ้าไม่มี)
bool found = dict.TryGetValue(2, out int val); // Safe: found=true, val=89
dict.Remove(3);
Array (T[])
- Fixed-size Sequential Collection
- Same Type Elements
- Contiguous Memory
- Index-based Access (0-based) O(1)
- Size ไม่เปลี่ยนแปลงได้หลังสร้าง
การประกาศและใช้งาน
// Declaration + Init
int[] arr = new int[5]; // Size 5, Default 0
int[] arr2 = new int[5] { 3, 5, 35, 87, 56 }; // Init with Values
int[] arr3 = { 3, 5, 35, 87, 56 }; // Implicit Size
// Access
arr[0] = 10;
int val = arr[2];
// Iterate
foreach (int x in arr) { }
for (int i = 0; i < arr.Length; i++) { }
Comparison Table
| Feature | Dictionary<K,V> | Array (T[]) |
|---|---|---|
| Access By | Key (Any Type) | Index (int) |
| Key Type | Any (Must Implement GetHashCode/Equals) | Integer Only (0..Length-1) |
| Size | Dynamic | Fixed |
| Duplicate Keys | ❌ Not Allowed | N/A (Index Unique) |
| Order Preserved | ✅ Insertion Order (.NET Core 3.0+) | ✅ Yes |
| Lookup Speed | O(1) Average | O(1) by Index |
| Memory Overhead | Higher (Hash Table) | Minimal (Contiguous) |
| Use Case | Key-Value Lookup, Mapping, Caching | Sequential Data, Fixed Size, Performance Critical |
เมื่อไหร่ควรใช้ไหน?
- Dictionary: ID → Object, Config Settings, Caching, Counting Frequency, Grouping
- Array: Buffer, Matrix, Fixed-size Buffer, High-performance Numeric Computing, Interop
- List<T>: Dynamic Array (เพิ่ม/ลบได้) — ใช้แทน Array ส่วนใหญ่
ตัวอย่าง: Count Word Frequency (Dictionary)
string text = "apple banana apple cherry banana apple";
var freq = new Dictionary();
foreach (string word in text.Split(' ')) {
freq[word] = freq.GetValueOrDefault(word) + 1;
}
// freq: { ["apple", 3], ["banana", 2], ["cherry", 1] }
ตัวอย่าง: Image Pixel Buffer (Array)
// 100x100 RGB Image = 30,000 bytes
byte[] pixels = new byte[100 * 100 * 3];
int index = (y * width + x) * 3;
pixels[index] = R;
pixels[index + 1] = G;
pixels[index + 2] = B;