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

Set (Tập hợp) trong C# - HashSet

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ới
  • Remove(item) - xóa
  • Contains(item) - kiểm tra tồn tại O(1)
  • UnionWith(other) - hợp
  • IntersectWith(other) - giao
  • ExceptWith(other) - hiệu
  • IsSubsetOf, IsSupersetOf, Overlaps

SortedSet<T>: Tự động sắp xếp, O(log n) operations.