ภาพรวม
SortedList ใน namespace System.Collections เก็บคู่คีย์-ค่า並รักษาลำดับตามคีย์ เมธอด GetValueList() คืนค่า IList ที่มีค่าทั้งหมดเรียงตามลำดับคีย์
ตัวอย่างที่ 1: ดึงรายการค่าจาก SortedList แบบ int
using System;
using System.Collections;
public class Demo
{
public static void Main(String[] args)
{
SortedList list = new SortedList();
list.Add("A", 1);
list.Add("B ", 2);
list.Add("C ", 3);
list.Add("D", 4);
list.Add("E", 5);
list.Add("F", 6);
list.Add("G", 7);
list.Add("H", 8);
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(int res in col)
Console.WriteLine(res);
}
}
ผลลัพธ์
SortedList elements...
A 1
B 2
C 3
D 4
E 5
F 6
G 7
H 8
List of values...SortedList
1
2
3
4
5
6
7
8
ตัวอย่างที่ 2: ดึงรายการค่าจาก SortedList แบบสตริง
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);
}
}
ผลลัพธ์
SortedList elements...
Five Sales
Four Purchase
One IT
Six Finance
Three Marketing
Two Operations
List of values...SortedList
Sales
Purchase
IT
Finance
Marketing
Operations
คำอธิบายเพิ่มเติม
GetValueList()คืนค่า IList ที่เป็นมุมมอง (view) ของค่า ไม่ใช่สำเนา การเปลี่ยนแปลง SortedList จะสะท้อนใน IList นี้- ค่าจะเรียงตามลำดับคีย์ (sorted by key) ไม่ใช่ลำดับการเพิ่ม
- SortedList ใช้ binary search สำหรับการค้นหา O(log n) เหมาะสำหรับข้อมูลที่ต้องการเรียงลำดับและค้นหาบ่อย
- สำหรับโค้ดใหม่ แนะนำ
SortedDictionary<TKey, TValue>หรือSortedList<TKey, TValue>(generic)