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

โครงสร้างข้อมูลสำเร็จรูป (Inbuilt Data Structures) ใน C#

โครงสร้างข้อมูลสำเร็จรูปใน 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 AccessList<T>Access O(1), Insert/Remove O(n)
Key-Value Lookup เร็วDictionary<TKey, TValue>O(1) average
Unique values, Set opsHashSet<T>O(1)
FIFO QueueQueue<T>Enqueue/Dequeue O(1)
LIFO StackStack<T>Push/Pop O(1)
Sorted Keys/ValuesSortedDictionary/SortedSetO(log n)
Thread-SafeConcurrent*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