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

Tạo SortedSet trong C#

Giới thiệu

SortedSet<T> (namespace System.Collections.Generic) là tập hợp các phần tử duy nhất, tự động sắp xếp theo thứ tự tăng dần (theo IComparer<T>). Phù hợp khi cần tập hợp đã sắp xếp và truy xuất nhanh min/max.

Ví dụ 1: Tạo và duyệt SortedSet

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("Các phần tử trong 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("Các phần tử trong SortedSet2 (Enumerator cho SortedSet)...");
        SortedSet.Enumerator demoEnum = set2.GetEnumerator();
        while (demoEnum.MoveNext())
        {
            string res = demoEnum.Current;
            Console.WriteLine(res);
        }
    }
}

Kết quả

Các phần tử trong SortedSet1...
AB
BC
CD
EF
Các phần tử trong SortedSet2 (Enumerator cho SortedSet)...
AB
BC
CD
DE
EF
HI
JK

Ví dụ 2: SortedSet với RemoveWhere

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool Demo(int i)
    {
        return ((i % 10) == 0);
    }

    public static void Main(string[] args)
    {
        SortedSet set1 = new SortedSet();
        set1.Add(200);
        set1.Add(215);
        set1.Add(310);
        set1.Add(500);
        set1.Add(600);

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

        Console.WriteLine(" ");
        set1.RemoveWhere(Demo); // xóa các số chia hết cho 10
        Console.WriteLine("SortedSet sau khi xóa một số phần tử...");
        foreach (int i in set1)
        {
            Console.WriteLine(i);
        }
    }
}

Kết quả

Các phần tử SortedSet...
200
215
310
500
600
SortedSet sau khi xóa một số phần tử...
215

Đặc điểm nổi bật

  • Tự động loại bỏ trùng lặp.
  • Luôn giữ thứ tự sắp xếp.
  • Hỗ trợ Min, Max, GetViewBetween, RemoveWhere.
  • Phức tạp thêm/xóa/tìm kiếm: O(log n).