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

Kiểm tra SortedSet có phải tập con của tập hợp chỉ định trong C#

Phương thức IsSubsetOf của SortedSet<T> xác định xem tập hợp hiện tại có phải là tập con của tập hợp khác hay không (tất cả phần tử của tập này đều nằm trong tập kia).

Ví dụ 1: Tập con hợp lệ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet();
        set1.Add("AB"); set1.Add("BC"); set1.Add("CD"); set1.Add("EF");

        Console.WriteLine("Phần tử SortedSet1...");
        foreach (string res in set1) Console.WriteLine(res);

        SortedSet set2 = new SortedSet();
        set2.Add("BC"); set2.Add("CD"); set2.Add("DE"); set2.Add("EF");
        set2.Add("AB"); set2.Add("HI"); set2.Add("JK");

        Console.WriteLine("Phần tử SortedSet2...");
        foreach (string res in set2) Console.WriteLine(res);

        Console.WriteLine("SortedSet1 là tập con của SortedSet2? = " + set1.IsSubsetOf(set2));
    }
}

Kết quả

Phần tử SortedSet1... AB BC CD EF
Phần tử SortedSet2... AB BC CD DE EF HI JK
SortedSet1 là tập con của SortedSet2? = True

Ví dụ 2: Tập con với phần tử trùng lặp

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet set1 = new SortedSet();
        set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); set1.Add("CD"); // Chỉ giữ 1 "CD"

        Console.WriteLine("Phần tử SortedSet1...");
        foreach (string res in set1) Console.WriteLine(res);

        SortedSet set2 = new SortedSet();
        set2.Add("BC"); set2.Add("CD"); set2.Add("DE"); set2.Add("EF");
        set2.Add("AB"); set2.Add("HI"); set2.Add("JK");

        Console.WriteLine("Phần tử SortedSet2...");
        foreach (string res in set2) Console.WriteLine(res);

        Console.WriteLine("SortedSet1 là tập con của SortedSet2? = " + set1.IsSubsetOf(set2));
    }
}

Kết quả

Phần tử SortedSet1... CD
Phần tử SortedSet2... AB BC CD DE EF HI JK
SortedSet1 là tập con của SortedSet2? = True

Lưu ý: SortedSet tự động loại bỏ trùng lặp và sắp xếp theo thứ tự.