Array có kích thước cố định. List<T> linh hoạt hơn và dùng rất thường xuyên.
Chọn collection theo cách truy cập dữ liệu.
| Collection | Công dụng | Ví dụ |
|---|
| Array | Danh sách cố định | int[] nums = { 1, 2 }; |
List<T> | Danh sách thay đổi kích thước | new List<string>() |
Dictionary<TKey,TValue> | Tra cứu theo key | users["id"] |
HashSet<T> | Tập không trùng | new HashSet<int>() |
Queue<T> | Vào trước ra trước | Enqueue, Dequeue |
Stack<T> | Vào sau ra trước | Push, Pop |
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[0]);
var names = new List<string> { "An", "Binh" };
Console.WriteLine(names.Count);
var scores = new Dictionary<string, int>
Console.WriteLine(scores["An"]);
var uniqueIds = new HashSet<int> { 1, 2, 2 };
Console.WriteLine(uniqueIds.Contains(2));
| Thao tác | Ví dụ |
|---|
Add | list.Add("new") |
Remove | list.Remove("old") |
Contains | list.Contains("An") |
Count | list.Count |
Clear | list.Clear() |
Sort | list.Sort() |
| Nhu cầu | Collection phù hợp |
|---|
| Danh sách theo thứ tự, thêm/xóa thường xuyên | List<T> |
| Tra cứu theo key | Dictionary<TKey, TValue> |
| Không cho trùng | HashSet<T> |
| Hàng đợi xử lý job | Queue<T> |
| Undo/history | Stack<T> |
| Dữ liệu cố định, hiệu năng index tốt | Array |
if (scores.TryGetValue("An", out int score))
Console.WriteLine(score);
scores["Chi"] = 10; // thêm mới hoặc ghi đè
bool exists = scores.ContainsKey("Chi");
var a = new HashSet<int> { 1, 2, 3 };
var b = new HashSet<int> { 3, 4 };
a.UnionWith(b); // {1, 2, 3, 4}
var users = new List<User>
public record User(string Name, int Age);
- Truy cập index ngoài phạm vi array/list.
- Dùng
Dictionary[key] khi key chưa tồn tại; nên kiểm tra ContainsKey.
- Nhầm
Queue với Stack.
- Xóa phần tử khi đang
foreach.
- Dùng
List.Contains cho lookup lớn; cân nhắc HashSet.
array, mảng, collection, List, Dictionary, TryGetValue, ContainsKey, HashSet, Queue, Stack, Add, Remove, Contains, Count, Clear, Sort, collection initializer