C# dùng HashSet<T> cho Set - tập hợp không trùng lặp, lookup O(1).
Khai báo và loại bỏ trùng
string[] arr1 = { "Table", "Chair", "Pen", "Clip", "Table" };
var h = new HashSet<string>(arr1);
string[] arr2 = h.ToArray();
Ví dụ
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
string[] arr1 = { "Table", "Chair", "Pen", "Clip", "Table" };
Console.WriteLine("Gốc: " + string.Join(",", arr1));
var h = new HashSet<string>(arr1);
string[] arr2 = h.ToArray();
Console.WriteLine("Sau HashSet: " + string.Join(",", arr2));
}
}
Kết quả
Gốc: Table,Chair,Pen,Clip,Table Sau HashSet: Table,Chair,Pen,Clip
Operations phổ biến
Add(item)- thêm, trả true nếu mớiRemove(item)- xóaContains(item)- kiểm tra tồn tại O(1)UnionWith(other)- hợpIntersectWith(other)- giaoExceptWith(other)- hiệuIsSubsetOf,IsSupersetOf,Overlaps
SortedSet<T>: Tự động sắp xếp, O(log n) operations.