Bỏ qua để đến nội dung

Mảng và Collection

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.

CollectionCông dụngVí dụ
ArrayDanh sách cố địnhint[] nums = { 1, 2 };
List<T>Danh sách thay đổi kích thướcnew List<string>()
Dictionary<TKey,TValue>Tra cứu theo keyusers["id"]
HashSet<T>Tập không trùngnew HashSet<int>()
Queue<T>Vào trước ra trướcEnqueue, Dequeue
Stack<T>Vào sau ra trướcPush, Pop
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[0]);
var names = new List<string> { "An", "Binh" };
names.Add("Chi");
names.Remove("An");
Console.WriteLine(names.Count);
var scores = new Dictionary<string, int>
{
["An"] = 9,
["Binh"] = 8
};
Console.WriteLine(scores["An"]);
var uniqueIds = new HashSet<int> { 1, 2, 2 };
Console.WriteLine(uniqueIds.Contains(2));
Thao tácVí dụ
Addlist.Add("new")
Removelist.Remove("old")
Containslist.Contains("An")
Countlist.Count
Clearlist.Clear()
Sortlist.Sort()
Nhu cầuCollection phù hợp
Danh sách theo thứ tự, thêm/xóa thường xuyênList<T>
Tra cứu theo keyDictionary<TKey, TValue>
Không cho trùngHashSet<T>
Hàng đợi xử lý jobQueue<T>
Undo/historyStack<T>
Dữ liệu cố định, hiệu năng index tốtArray
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>
{
new("An", 20),
new("Binh", 21)
};
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