SortedSet<T> มี property Count คืนค่าจำนวนสมาชิกในเซต ทำงานใน O(1) นอกจากนี้ยังมี Min และ Max สำหรับค่าต่ำสุด/สูงสุด (O(1) เพราะเรียงลำดับแล้ว)
ตัวอย่างโค้ดที่ 1: นับจำนวนและวนลูป
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("Elements in SortedSet1...");
foreach (string res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Count of elements in 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("Elements in SortedSet2 (Enumerator for SortedSet)...");
SortedSet.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
Console.WriteLine("Count of elements in SortedSet2 = " + set2.Count);
}
}
ผลลัพธ์
Elements in SortedSet1...
AB
BC
CD
EF
Count of elements in SortedSet1 = 4
Elements in SortedSet2 (Enumerator for SortedSet)...
AB
BC
CD
DE
EF
HI
JK
Count of elements in SortedSet2 = 7
ตัวอย่างโค้ดที่ 2: 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("Elements in SortedSet...");
foreach (int res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Count of elements in SortedSet = " + set1.Count);
set1.Clear();
Console.WriteLine("Count of elements in SortedSet (updated) = " + set1.Count);
}
}
ผลลัพธ์
Elements in SortedSet...
100
200
300
400
Count of elements in SortedSet = 4
Count of elements in SortedSet (updated) = 0
คุณสมบัติสำคัญของ SortedSet<T>
| Property/Method | คำอธิบาย | Complexity |
Count | จำนวนสมาชิก | O(1) |
Min | ค่าต่ำสุด | O(1) |
Max | ค่าสูงสุด | O(1) |
Add(T) | เพิ่ม (false หากซ้ำ) | O(log n) |
Remove(T) | ลบ (false หากไม่พบ) | O(log n) |
Contains(T) | ตรวจสอบมีอยู่ | O(log n) |
Clear() | ลบทั้งหมด | O(n) |
RemoveWhere(Predicate<T>) | ลบตามเงื่อนไข | O(n log n) |
Set Operations (O(n log n) หรือ O(n+m))
UnionWith(other) - ยูเนียน (รวม)
IntersectWith(other) - อินเตอร์เซกชัน (ร่วม)
ExceptWith(other) - ความต่าง (a - b)
SymmetricExceptWith(other) - ความต่างสมมาตร (a Δ b)
IsSubsetOf(other), IsSupersetOf(other), IsProperSubsetOf, IsProperSupersetOf, Overlaps, SetEquals
SortedSet vs HashSet vs List
| คุณสมบัติ | SortedSet<T> | HashSet<T> | List<T> |
| Unique | Yes | Yes | No |
| Sorted | Yes | No | No |
| Add/Remove/Contains | O(log n) | O(1) | O(n)/O(1) |
| Min/Max | O(1) | O(n) | O(n) |
| Index access | No | No | O(1) |