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

Thêm phần tử vào SortedSet trong C#

Giới thiệu

SortedSet<T> là tập hợp không trùng lặp, tự động sắp xếp các phần tử theo thứ tự tăng dần. Để thêm phần tử, sử dụng phương thức Add(T). Nếu phần tử đã tồn tại, nó sẽ bị bỏ qua.

Ví dụ 1: SortedSet số nguyên

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);
        set1.Add(400);

        Console.WriteLine("Các phần tử trong SortedSet...");
        foreach (int res in set1)
            Console.WriteLine(res);

        Console.WriteLine("SortedSet có chứa phần tử 500 không? = " + set1.Contains(500));
    }
}

Kết quả

Các phần tử trong SortedSet...
100
200
300
400
SortedSet có chứa phần tử 500 không? = False

Ví dụ 2: SortedSet chuỗi và kiểm tra siêu tập

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        SortedSet<string> set1 = new SortedSet<string>();
        set1.Add("CD");
        set1.Add("CD"); // Trùng lặp, bỏ qua
        set1.Add("CD");
        set1.Add("CD");

        Console.WriteLine("Các phần tử trong SortedSet1...");
        foreach (string res in set1)
            Console.WriteLine(res);

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

        Console.WriteLine("Các phần tử trong SortedSet2...");
        foreach (string res in set2)
            Console.WriteLine(res);

        Console.WriteLine("SortedSet2 có phải siêu tập của SortedSet1 không? = " + set2.IsSupersetOf(set1));
    }
}

Kết quả

Các phần tử trong SortedSet1...
CD
Các phần tử trong SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 có phải siêu tập của SortedSet1 không? = True

Lưu ý: SortedSet<T> yêu cầu kiểu T triển khai IComparable<T> hoặc cung cấp IComparer<T> khi khởi tạo. Thứ tự sắp xếp mặc định là tăng dần.