Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Collection (Tập hợp) trong C#

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):

ClassMô tả
ArrayListDanh sách động, index truy cập, lưu object.
HashtableKey-value pairs, truy cập bằng key (hash code).
SortedListKey-value pairs, sắp xếp theo key, truy cập key/index.
BitArrayMảng bit (0/1), compact memory.
StackLIFO (last-in-first-out).
QueueFIFO (first-in-first-out).

Generic collections (khuyến nghị, System.Collections.Generic):

  • List<T> - thay ArrayList
  • Dictionary<TKey,TValue> - thay Hashtable
  • SortedList<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).