Giới thiệu
Thuộc tính Max của SortedSet<T> trả về phần tử lớn nhất theo thứ tự sắp xếp. Min trả về nhỏ nhất. Cả hai O(1).
Ví dụ 1: SortedSet Max
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ử SortedSet1...");
foreach (string res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Phần tử lớn nhất SortedSet1 = " + set1.Max);
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ử SortedSet2 (Enumerator)...");
SortedSet.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Phần tử lớn nhất SortedSet2 = " + set2.Max);
}
}
Kết quả
Các phần tử SortedSet1...
AB
BC
CD
EF
Phần tử lớn nhất SortedSet1 = EF
Các phần tử SortedSet2 (Enumerator)...
AB
BC
CD
DE
EF
HI
JK
Phần tử lớn nhất SortedSet2 = JK
Ví dụ 2: SortedSet Min/Max
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet set1 = new SortedSet();
set1.Add(5);
set1.Add(50);
set1.Add(20);
set1.Add(10);
set1.Add(70);
set1.Add(60);
set1.Add(55);
set1.Add(95);
Console.WriteLine("Các phần tử SortedSet...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Phần tử lớn nhất SortedSet = " + set1.Max);
Console.WriteLine("Phần tử nhỏ nhất SortedSet = " + set1.Min);
}
}
Kết quả
Các phần tử SortedSet...
5
10
20
50
55
60
70
95
Phần tử lớn nhất SortedSet = 95
Phần tử nhỏ nhất SortedSet = 5
Lưu ý
- Nếu set rỗng,
Max/Minném exception. - Có thể cung cấp
IComparer<T>tùy chỉnh khi khởi tạo để thay đổi thứ tự sắp xếp. SortedSetkhông cho trùng lặp;Addtrả về false nếu đã tồn tại.