Giới thiệu
Thuộc tính Count của SortedSet<T> trả về số lượng phần tử hiện có. Do SortedSet không cho trùng lặp, Count chính là số phần tử duy nhất.
Ví dụ 1: Hai SortedSet, đếm và enumerator
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("Số phần tử SortedSet1 = " + set1.Count);
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 cho SortedSet)...");
SortedSet.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Số phần tử SortedSet2 = " + set2.Count);
}
}
Kết quả
Các phần tử SortedSet1...
AB
BC
CD
EF
Số phần tử SortedSet1 = 4
Các phần tử SortedSet2 (Enumerator cho SortedSet)...
AB
BC
CD
DE
EF
HI
JK
Số phần tử SortedSet2 = 7
Ví dụ 2: SortedSet, Clear
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet set1 = new SortedSet();
set1.Add(100);
set1.Add(200);
set1.Add(300);
set1.Add(400);
Console.WriteLine("Các phần tử SortedSet...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Số phần tử SortedSet = " + set1.Count);
set1.Clear();
Console.WriteLine("Số phần tử SortedSet (cập nhật) = " + set1.Count);
}
}
Kết quả
Các phần tử SortedSet...
100
200
300
400
Số phần tử SortedSet = 4
Số phần tử SortedSet (cập nhật) = 0
Phương thức liên quan
Add(T)– thêm, trả về false nếu đã tồn tại.Remove(T)– xóa, trả về bool.RemoveWhere(Predicate<T>)– xóa theo điều kiện.Min,Max– phần tử nhỏ nhất/lớn nhất (O(1)).