Collection classes là các lớp chuyên biệt cho lưu trữ và truy xuất dữ liệu. Hỗ trợ stack, queue, list, hash table. Hầu hết implement các interface chung (ICollection, IEnumerable, IList, IDictionary).
Các collection class chính (non-generic, trong System.Collections):
| Class | Mô tả |
|---|---|
| ArrayList | Danh sách động, index truy cập, lưu object. |
| Hashtable | Key-value pairs, truy cập bằng key (hash code). |
| SortedList | Key-value pairs, sắp xếp theo key, truy cập key/index. |
| BitArray | Mảng bit (0/1), compact memory. |
| Stack | LIFO (last-in-first-out). |
| Queue | FIFO (first-in-first-out). |
Generic collections (khuyến nghị, System.Collections.Generic):
List<T>- thay ArrayListDictionary<TKey,TValue>- thay HashtableSortedList<TKey,TValue>/SortedDictionary<TKey,TValue>Stack<T>,Queue<T>HashSet<T>,LinkedList<T>,ConcurrentQueue<T>...
Ví dụ ArrayList
using System;
using System.Collections;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
al.Add(99); al.Add(76); al.Add(87); al.Add(46); al.Add(55);
Console.WriteLine("Capacity: {0}", al.Capacity); // 8
Console.WriteLine("Count: {0}", al.Count); // 5
Console.Write("Elements: ");
foreach (int i in al) Console.Write(i + " ");
Console.ReadKey();
}
}
}
Kết quả
Capacity: 8
Count: 5
Elements: 99 76 87 46 55
Lưu ý: Capacity ≥ Count. Mặc định capacity=4, tự động gấp đôi khi đầy. Generic collections type-safe, hiệu năng tốt hơn (không boxing/unboxing).