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

ความแตกต่างระหว่าง Dictionary และ Array ใน C#

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

FeatureDictionary<K,V>Array (T[])
Access ByKey (Any Type)Index (int)
Key TypeAny (Must Implement GetHashCode/Equals)Integer Only (0..Length-1)
SizeDynamicFixed
Duplicate Keys❌ Not AllowedN/A (Index Unique)
Order Preserved✅ Insertion Order (.NET Core 3.0+)✅ Yes
Lookup SpeedO(1) AverageO(1) by Index
Memory OverheadHigher (Hash Table)Minimal (Contiguous)
Use CaseKey-Value Lookup, Mapping, CachingSequential 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;