Lớp SortedSet<T> đại diện cho tập hợp các đối tượng được duy trì theo thứ tự đã sắp xếp.
Thuộc tính
| STT | Thuộc tính & Mô tả |
| 1 | Comparer: Đối tượng IComparer<T> dùng để sắp xếp. |
| 2 | Count: Số phần tử trong tập hợp. |
| 3 | Max: Giá trị lớn nhất theo comparer. |
| 4 | Min: Giá trị nhỏ nhất theo comparer. |
Phương thức chính
| STT | Phương thức & Mô tả |
| 1 | Add(T): Thêm phần tử, trả về true nếu thêm thành công. |
| 2 | Clear(): Xóa tất cả phần tử. |
| 3 | Contains(T): Kiểm tra phần tử tồn tại. |
| 4 | CopyTo(T[]): Sao chép toàn bộ vào mảng. |
| 5 | CopyTo(T[], Int32): Sao chép từ chỉ số mảng chỉ định. |
| 6 | CopyTo(T[], Int32, Int32): Sao chép số lượng chỉ định. |
| 7 | CreateSetComparer(): Trả về IEqualityComparer cho tập hợp các tập hợp. |
Ví dụ 1: Kiểm tra chứa phần tử
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 sẽ bị bỏ qua
set1.Add("CD");
set1.Add("CD");
Console.WriteLine("Các phần tử SortedSet1...");
foreach (string res in set1) {
Console.WriteLine(res);
}
Console.WriteLine("SortedSet1 chứa 'DE'? = " + set1.Contains("DE"));
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ử 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ử SortedSet1...
CD
SortedSet1 chứa 'DE'? = False
Các phần tử SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 là siêu tập của SortedSet1? = True
Ví dụ 2: Sử dụng Enumerator
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(){
SortedSet<string> set1 = new SortedSet<string>();
set1.Add("AB");
set1.Add("BC");
set1.Add("CD");
set1.Add("EF");
Console.WriteLine("Các phần tử 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ử SortedSet2 (Enumerator)...");
SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext()) {
string res = demoEnum.Current;
Console.WriteLine(res);
}
}
}
Kết quả
Các phần tử SortedSet1...
AB
BC
CD
EF
Các phần tử SortedSet2 (Enumerator)...
AB
BC
CD
DE
EF
HI
JK