Generic Collections ใน Namespace System.Collections.Generic ให้ Type Safety และ Performance ดีกว่า Non-generic (System.Collections)
1. List<T> - Dynamic Array
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> myList = new List<string>()
{ "one", "two", "three", "four", "five", "six" };
Console.WriteLine("Count: " + myList.Count); // 6
myList.Add("seven");
myList.Remove("two");
foreach (var item in myList)
Console.WriteLine(item);
}
}
2. SortedList<TKey, TValue> - Sorted Key-Value
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
SortedList<string, string> sl = new SortedList<string, string>();
sl.Add("001", "Tim");
sl.Add("002", "Steve");
sl.Add("003", "Bill");
sl.Add("004", "Tom");
if (sl.ContainsValue("Bill"))
Console.WriteLine("This name is already in the list");
else
sl.Add("005", "James");
foreach (var kvp in sl)
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
}
Generic Collections หลัก
| Collection | คำอธิบาย | Non-generic Equivalent |
|---|---|---|
| List<T> | Dynamic Array, เข้าถึงโดย Index | ArrayList |
| Dictionary<TKey,TValue> | Key-Value, Fast Lookup O(1) | Hashtable |
| SortedList<TKey,TValue> | Key-Value เรียงตาม Key | SortedList |
| Queue<T> | FIFO (First-In-First-Out) | Queue |
| Stack<T> | LIFO (Last-In-First-Out) | Stack |
| HashSet<T> | Unique Values, Set Operations | - |
| LinkedList<T> | Doubly Linked List | - |
ทำไมต้องใช้ Generic Collections
- Type Safety - Error ตอน Compile ไม่ใช่ Runtime
- Performance - ไม่ต้อง Boxing/Unboxing (Value Types)
- Code Clarity - รู้ชนิดข้อมูลใน Collection ชัดเจน