ภาพรวม
SortedSet<T> (ใน System.Collections.Generic) คือคอลเลกชันที่ไม่มีค่าซ้ำ และจัดเรียงสมาชิกอัตโนมัติตามลำดับ (ใช้ comparer)
คุณสมบัติหลัก
| ลำดับ | คุณสมบัติ | คำอธิบาย |
| 1 | Comparer | IComparer<T> ที่ใช้เรียงลำดับ |
| 2 | Count | จำนวนสมาชิก |
| 3 | Max | ค่าสูงสุดตาม comparer |
| 4 | Min | ค่าต่ำสุดตาม comparer |
เมธอดหลัก
| ลำดับ | เมธอด | คำอธิบาย |
| 1 | Add(T) | เพิ่มสมาชิก คืน true ถ้าเพิ่มสำเร็จ (ไม่ซ้ำ) |
| 2 | Clear() | ลบทั้งหมด |
| 3 | Contains(T) | ตรวจสอบว่ามีสมาชิกหรือไม่ |
| 4 | CopyTo(T[]) | คัดลอกไปอาร์เรย์ |
| 5 | CopyTo(T[], Int32) | คัดลอกไปอาร์เรย์จากดัชนี |
| 6 | CopyTo(T[], Int32, Int32) | คัดลอกจำนวนที่กำหนดจากดัชนี |
| 7 | CreateSetComparer() | คืน IEqualityComparer สำหรับเซตของเซต |
ตัวอย่างที่ 1: ตรวจสอบ Contains และ IsSupersetOf
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"); // ซ้ำ จะเพิ่มแค่ครั้งแรก
set1.Add("CD");
set1.Add("CD");
Console.WriteLine("Elements in SortedSet1...");
foreach (string res in set1)
{
Console.WriteLine(res);
}
Console.WriteLine("Does the SortedSet1 contains the element 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("Elements in SortedSet2...");
foreach (string res in set2)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet2 is a superset of SortedSet1? = " + set2.IsSupersetOf(set1));
}
}
ผลลัพธ์
Elements in SortedSet1...
CD
Does the SortedSet1 contains the element DE? = False
Elements in SortedSet2...
AB
BC
CD
DE
EF
HI
JK
SortedSet2 is a superset of SortedSet1? = True
ตัวอย่างที่ 2: ใช้ Enumerator วนลูป SortedSet
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("Elements in 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("Elements in SortedSet2 (Enumerator for SortedSet)...");
SortedSet<string>.Enumerator demoEnum = set2.GetEnumerator();
while (demoEnum.MoveNext())
{
string res = demoEnum.Current;
Console.WriteLine(res);
}
}
}
ผลลัพธ์
Elements in SortedSet1...
AB
BC
CD
EF
Elements in SortedSet2 (Enumerator for SortedSet)...
AB
BC
CD
DE
EF
HI
JK
สรุป
- SortedSet ไม่อนุญาตค่าซ้ำ และเรียงลำดับอัตโนมัติ
- มีเมธอดเซต:
UnionWith, IntersectWith, ExceptWith, SymmetricExceptWith, IsSubsetOf, IsSupersetOf, Overlaps, SetEquals
- ประสิทธิภาพ O(log n) สำหรับ Add, Contains, Remove