ความแตกต่างระหว่าง List และ Dictionary ใน C#
ทั้งคู่อยู่ใน System.Collections.Generic และเป็น Generic Collections แต่มีโครงสร้างและกรณีใช้งานต่างกัน
List<T> - รายการลำดับ
- เก็บข้อมูลแบบลำดับ (ordered sequence)
- เข้าถึงด้วยดัชนี (index-based):
list[0],list[5] - อนุญาตให้มีค่าซ้ำได้
- ขนาดปรับเปลี่ยนได้ (dynamic size)
- เหมาะสำหรับ: รายการที่ต้องเรียงลำดับ, ต้องเข้าถึงบ่อยด้วยดัชนี, ต้องวนลูปบ่อย
List subjects = new List { "Math", "English", "Science" };
subjects.Add("History");
string first = subjects[0]; // "Math"
Dictionary<TKey, TValue> - คู่คีย์-ค่า
- เก็บข้อมูลเป็นคู่ Key-Value (แผนที่/Map)
- เข้าถึงด้วย Key:
dict["key"] - Key ต้องไม่ซ้ำ (unique keys)
- ค้นหาโดย Key เร็วมาก O(1) (Hash table)
- ไม่มีลำดับที่รับประกัน (unordered)
- เหมาะสำหรับ: ค้นหาค่าจาก Key, Mapping, Lookup table
Dictionary scores = new Dictionary();
scores.Add("Alice", 95);
scores.Add("Bob", 87);
int aliceScore = scores["Alice"]; // 95 - O(1)
ตารางเปรียบเทียบ
| คุณสมบัติ | List<T> | Dictionary<TKey, TValue> |
|---|---|---|
| โครงสร้าง | ลำดับ (Sequence) | Key-Value Pair (Map) |
| การเข้าถึง | Index (0-based) | Key |
| ความเร็วการค้นหา | O(n) - ต้องวนลูป | O(1) - Hash lookup |
| ค่าซ้ำ | อนุญาต | Key ไม่ซ้ำ, Value ซ้ำได้ |
| ลำดับ | รักษาลำดับการเพิ่ม | ไม่รับประกันลำดับ (ใช้ OrderedDictionary ถ้าต้องการ) |
| หน่วยความจำ | น้อยกว่า | มากกว่า (Hash table overhead) |
| การวนลูป | เร็ว, เรียบง่าย | วนผ่าน Keys, Values, หรือ KeyValuePair |
เมื่อไหร่ควรใช้อะไร?
// ใช้ List เมื่อ:
// - ต้องการเก็บรายการตามลำดับ
// - ต้องเข้าถึงด้วยตำแหน่ง (index)
// - ต้องการอนุญาตค่าซ้ำ
// - ต้องการ Sort, Reverse, BinarySearch
List numbers = new List { 1, 2, 3, 2, 1 }; // ซ้ำได้
// ใช้ Dictionary เมื่อ:
// - ต้องการ Map key -> value
// - ต้องค้นหาเร็วจาก key
// - Key เป็น unique identifier
// - ไม่สนใจลำดับ
Dictionary users = new Dictionary
{
[101] = "Alice",
[102] = "Bob"
};
// users[101] -> "Alice" (O(1))
โครงสร้างข้อมูลที่เกี่ยวข้อง
HashSet<T>- เซต ไม่ซ้ำ ไม่มีลำดับ O(1) lookupSortedList<TKey, TValue>- Dictionary เรียงตาม KeySortedDictionary<TKey, TValue>- BST-based sorted mapConcurrentDictionary<TKey, TValue>- Thread-safe