บทความนี้สาธิตวิธีการเพิ่มสมาชิก (element) ลงใน SortedSet<T> ซึ่งเป็นชุดข้อมูลที่จัดเก็บค่าไม่ซ้ำและจัดเรียงอัตโนมัติ
ตัวอย่างที่ 1: เพิ่มตัวเลขใน SortedSet
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
SortedSet<int> set1 = new SortedSet<int>();
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("Does the SortedSet contains the element 500? = " + set1.Contains(500));
}
}
ผลลัพธ์
Elements in SortedSet... 100 200 300 400 Does the SortedSet contains the element 500? = False
ตัวอย่างที่ 2: เพิ่มสตริงและตรวจสอบ Superset
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"); // duplicate - ไม่ถูกเพิ่ม
set1.Add("CD");
set1.Add("CD");
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...");
foreach (string res in set2)
{
Console.WriteLine(res);
}
Console.WriteLine("SortedSet2 is a superset of SortedSet1? = " + set2.IsSupersetOf(set1));
}
}
ผลลัพธ์
Elements in SortedSet1... CD Elements in SortedSet2... AB BC CD DE EF HI JK SortedSet2 is a superset of SortedSet1? = True
คำอธิบายเพิ่มเติม
SortedSet<T>ใช้ balanced binary search tree (Red-Black tree) ภายใน- ค่าจะถูกจัดเรียงอัตโนมัติตามลำดับธรรมชาติ (natural order) ของ T
- ไม่อนุญาตค่าซ้ำ -
Add()คืนค่าfalseถ้าค่ามีอยู่แล้ว - เวลา complexity: Add/Remove/Contains = O(log n)
- มี method เซต:
UnionWith,IntersectWith,ExceptWith,IsSupersetOf,IsSubsetOf - ต้องการให้ T implement
IComparable<T>หรือส่งIComparer<T>เข้า constructor