Giới thiệu
Lớp SortedSet<T> cung cấp phương thức Contains(T item) để kiểm tra sự tồn tại của một phần tử. Phương thức này có độ phức tạp O(log n) nhờ cấu trúc cây cân bằng nội bộ.
Ví dụ 1
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet set1 = new SortedSet();
set1.Add("CD");
set1.Add("CD"); // Trùng lặp sẽ bị 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);
}
Console.WriteLine("SortedSet1 có chứa phần tử 'DE'? = " + set1.Contains("DE"));
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...");
foreach (string res in set2)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet2 là siêu tập của SortedSet1? = " + set2.IsSupersetOf(set1));
}
}
Kết quả
Các phần tử trong SortedSet1... CD SortedSet1 có chứa phần tử 'DE'? = False Các phần tử trong SortedSet2... AB BC CD DE EF HI JK SortedSet2 là siêu tập của SortedSet1? = True
Ví dụ 2
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet mySet = new SortedSet();
mySet.Add(100);
mySet.Add(200);
mySet.Add(300);
mySet.Add(400);
Console.WriteLine("Các phần tử trong SortedSet...");
foreach (int res in mySet)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet có chứa phần tử 400? = " + mySet.Contains(400));
}
}
Kết quả
Các phần tử trong SortedSet... 100 200 300 400 SortedSet có chứa phần tử 400? = True
Lưu ý quan trọng
SortedSettự động loại bỏ các phần tử trùng lặp.- Phương thức
Contains()hoạt động hiệu quả O(log n). - Có thể sử dụng
IsSupersetOf(),IsSubsetOf(),Overlaps()để kiểm tra quan hệ giữa các tập hợp. - Phần tử trong SortedSet phải implement
IComparable<T>hoặc cung cấpIComparer<T>khi khởi tạo.