SortedList มี property IsReadOnly ที่บอกว่าอินสแตนซ์นั้นเป็น read-only หรือไม่ โดยค่าเริ่มต้น SortedList ไม่ใช่ read-only (IsReadOnly = false) สามารถเพิ่ม/ลบ/แก้ไขข้อมูลได้เสมอ
ตัวอย่างโค้ด
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
SortedList list = new SortedList();
list.Add("One", "IT");
list.Add("Two", "Operations");
list.Add("Three", "Marketing");
list.Add("Four", "Purchase");
list.Add("Five", "Sales");
list.Add("Six", "Finance");
Console.WriteLine("SortedList elements...");
foreach (DictionaryEntry d in list)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nList of values...SortedList");
IList col = list.GetValueList();
foreach (string res in col)
{
Console.WriteLine(res);
}
Console.WriteLine("\nSortedList is read-only? = " + list.IsReadOnly);
}
}
ผลลัพธ์
SortedList elements...
Five Sales
Four Purchase
One IT
Six Finance
Three Marketing
Two Operations
List of values...SortedList
Sales
Purchase
IT
Finance
Marketing
Operations
SortedList is read-only? = False
ตัวอย่างเพิ่มเติม: ดู Keys และ Index
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
SortedList list = new SortedList();
list.Add("One", "Finance");
list.Add("Two", "Marketing");
list.Add("Three", "Sales");
list.Add("Four", "Purchase");
list.Add("Five", "Operations");
list.Add("Six", "IT");
Console.WriteLine("SortedList elements...");
foreach (DictionaryEntry d in list)
{
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nIndex at key One = " + list.IndexOfKey("One"));
ICollection col = list.Keys;
Console.WriteLine("\nCollection of Keys...");
foreach (string res in col)
Console.WriteLine(res);
Console.WriteLine("\nSortedList is read-only? = " + list.IsReadOnly);
}
}
ผลลัพธ์
SortedList elements...
Five Operations
Four Purchase
One Finance
Six IT
Three Sales
Two Marketing
Index at key One = 2
Collection of Keys...
Five
Four
One
Six
Three
Two
SortedList is read-only? = False
คุณสมบัติสำคัญของ SortedList
- IsReadOnly = false เสมอ (เว้นแต่จะ wrap ด้วย ReadOnly wrapper)
- IsFixedSize = false เสมอ - ขยายตัวได้
- IsSynchronized = false เสมอ - ไม่ thread-safe โดยค่าเริ่มต้น
- จัดเก็บคีย์-ค่า เรียงลำดับตามคีย์ (sorted by key)
- ใช้ array ด้านใน - เร็วกว่า SortedDictionary สำหรับข้อมูลน้อยและการเข้าถึงแบบ index
- ดัชนี (index) เริ่มจาก 0 ตามลำดับคีย์ที่เรียงแล้ว
SortedList vs SortedDictionary
| คุณสมบัติ | SortedList | SortedDictionary |
|---|---|---|
| โครงสร้างภายใน | 2 arrays (keys, values) | Red-Black Tree |
| Memory | น้อยกว่า | มากกว่า |
| Insert/Delete | O(n) - ต้อง shift array | O(log n) |
| Access by index | O(1) | ไม่รองรับโดยตรง |
| เหมาะสำหรับ | ข้อมูลน้อย, อ่านมาก เขียนน้อย | ข้อมูลเยอะ, เขียน/ลบ บ่อย |