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

Kiểm tra SortedSet và tập hợp có chứa cùng phần tử trong C#

Giới thiệu

Phương thức SetEquals(IEnumerable<T>) của SortedSet<T> kiểm tra xem hai tập hợp có chứa chính xác cùng các phần tử hay không. Khác với Overlaps (chỉ cần 1 phần tử chung), SetEquals yêu cầu hai tập hợp hoàn toàn giống nhau.

Ví dụ 1: Hai SortedSet khác nhau

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(450);
        set2.Add(550);
        set2.Add(650);
        set2.Add(750);
        set2.Add(800);
        
        Console.WriteLine("Does it contain the same elements? = " + set1.SetEquals(set2));
    }
}

Kết quả

Does it contain the same elements? = False

Ví dụ 2: Hai SortedSet giống nhau

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<int> set1 = new SortedSet<int>();
        set1.Add(100);
        set1.Add(200);
        set1.Add(300);
        
        SortedSet<int> set2 = new SortedSet<int>();
        set2.Add(100);
        set2.Add(200);
        set2.Add(300);
        
        Console.WriteLine("Does it contain the same elements? = " + set1.SetEquals(set2));
    }
}

Kết quả

Does it contain the same elements? = True

Đặc điểm SetEquals()

  • So sánh tập hợp (set equality): cùng phần tử, bỏ qua thứ tự
  • SortedSet đã sắp xếp, nhưng SetEquals không yêu cầu thứ tự giống nhau
  • Phức tạp: O(n) - duyệt tập hợp nhỏ hơn
  • Chấp nhận bất kỳ IEnumerable<T>
  • Không thay đổi tập hợp gốc

So sánh HashSet vs SortedSet - SetEquals

Đặc điểm HashSet<T> SortedSet<T>
SetEquals Có Có
Thứ tự nội bộ Không đảm bảo Đã sắp xếp
Hiệu suất Contains O(1) O(log n)
Yêu cầu T GetHashCode, Equals IComparable<T>

Các phép toán tập hợp khác

  • Overlaps(other) - Có giao nhau (ít nhất 1 phần tử chung)
  • IsSubsetOf(other) - Là tập con
  • IsSupersetOf(other) - Là tập cha
  • IsProperSubsetOf(other) - Tập con thực sự (khác other)
  • IsProperSupersetOf(other) - Tập cha thực sự
  • UnionWith(other) - Hợp (sửa đổi this)
  • IntersectWith(other) - Giao (sửa đổi this)
  • ExceptWith(other) - Hiệu (sửa đổi this)
  • SymmetricExceptWith(other) - Hiệu đối xứng