โครงสร้างข้อมูลสำเร็จรูปใน C# (System.Collections.Generic)
.NET Framework มีคอลเลกชันพร้อมใช้งานหลากหลาย รองรับ Generic (Type-safe) และ Non-generic
1. List<T> - Dynamic Array (ใช้บ่อยที่สุด)
- อาร์เรย์ขนาดไดนามิก เพิ่ม/ลบได้
- Random access O(1) ด้วย index
- เก็บค่าซ้ำได้ รักษาลำดับ
var list = new List { 1, 2, 3 };
list.Add(4); // เพิ่มท้าย
list.Insert(0, 0); // แทรกหน้า
list.Remove(2); // ลบค่าแรกที่เจอ
list.RemoveAt(0); // ลบที่ index
list.Sort(); // เรียงลำดับ
bool has = list.Contains(3); // O(n)
2. Dictionary<TKey, TValue> - Hash Map
- Key-Value pair, Key unique
- Lookup/Insert/Delete O(1) average
- ไม่รักษาลำดับ (ใช้ SortedDictionary ถ้าต้องการ)
var dict = new Dictionary
{
["apple"] = 10,
["banana"] = 20
};
dict["orange"] = 30; // Add/Update
int count = dict["apple"]; // 10 - throw KeyNotFoundException ถ้าไม่มี
bool found = dict.TryGetValue("grape", out int val); // Safe lookup
3. HashSet<T> - Unique Collection
- เก็บค่าไม่ซ้ำ (Set)
- O(1) Contains, Add, Remove
- ไม่รักษาลำดับ (ใช้ SortedSet ถ้าต้องการ)
- Set operations: Union, Intersect, Except, SymmetricExcept
var set = new HashSet { 1, 2, 2, 3 }; // {1, 2, 3}
set.Add(4);
set.Remove(2);
set.UnionWith(new[] { 3, 4, 5 }); // {1, 3, 4, 5}
4. Queue<T> - FIFO
- First-In-First-Out
Enqueueเพิ่มท้าย,Dequeueนำหน้า,Peekดูหน้า
var q = new Queue();
q.Enqueue("A"); q.Enqueue("B");
string first = q.Dequeue(); // "A"
string peek = q.Peek(); // "B" (ยังอยู่ในคิว)
5. Stack<T> - LIFO
- Last-In-First-Out
Pushใส่บนสุด,Popนำบนสุด,Peekดูบนสุด
var s = new Stack();
s.Push(1); s.Push(2);
int top = s.Pop(); // 2
top = s.Peek(); // 1
6. LinkedList<T> - Doubly Linked List
- Insert/Remove กลาง O(1) ถ้ามี Node reference
- ไม่มี Random Access (ต้องวนลูป)
- ใช้น้อย แต่มีประโยชน์บางกรณี (LRU Cache)
var ll = new LinkedList();
ll.AddLast(1);
ll.AddLast(2);
var node = ll.Find(1);
ll.AddAfter(node, 5); // 1, 5, 2
7. SortedSet<T> / SortedDictionary<TKey, TValue>
- รักษาลำดับเรียง (BST - Red-Black Tree)
- O(log n) สำหรับทุก operation
8. Concurrent Collections (Thread-Safe)
ConcurrentDictionary<TKey, TValue>ConcurrentQueue<T>,ConcurrentStack<T>,ConcurrentBag<T>BlockingCollection<T>- Producer/Consumer pattern
ตารางเลือกใช้ (Cheat Sheet)
| ต้องการ... | ใช้... | Complexity |
|---|---|---|
| List ลำดับ, Random Access | List<T> | Access O(1), Insert/Remove O(n) |
| Key-Value Lookup เร็ว | Dictionary<TKey, TValue> | O(1) average |
| Unique values, Set ops | HashSet<T> | O(1) |
| FIFO Queue | Queue<T> | Enqueue/Dequeue O(1) |
| LIFO Stack | Stack<T> | Push/Pop O(1) |
| Sorted Keys/Values | SortedDictionary/SortedSet | O(log n) |
| Thread-Safe | Concurrent* | Varies |
| Insert/Remove กลางบ่อย | LinkedList<T> | O(1) with node ref |
Non-Generic (Legacy - หลีกเลี่ยง)
ArrayList→ ใช้List<object>หรือList<T>Hashtable→ ใช้Dictionary<TKey, TValue>Queue,Stack→ ใช้ Generic versions
เหตุผล: Boxing/Unboxing overhead, ไม่ Type-safe, Obsolete