Giới thiệu
SortedList (namespace System.Collections) lưu cặp khóa-giá trị, tự sắp xếp theo khóa. Phương thức Add(key, value) thêm cặp mới; khóa không được trùng.
Ví dụ 1: Thêm 10 cặp, lấy Keys và Values
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
SortedList list = new SortedList();
list.Add("A", "Jacob");
list.Add("B", "Sam");
list.Add("C", "Tom");
list.Add("D", "John");
list.Add("E", "Tim");
list.Add("F", "Mark");
list.Add("G", "Gary");
list.Add("H", "Nathan");
list.Add("I", "Shaun");
list.Add("J", "David");
ICollection col1 = list.Values;
Console.WriteLine("Các giá trị...");
foreach (string s in col1)
Console.WriteLine(s);
ICollection col2 = list.Keys;
Console.WriteLine("\nCác khóa...");
foreach (string s in col2)
Console.WriteLine(s);
}
}
Kết quả
Các giá trị...
Jacob
Sam
Tom
John
Tim
Mark
Gary
Nathan
Shaun
David
Các khóa...
A
B
C
D
E
F
G
H
I
J
Ví dụ 2: Thêm, xóa tại index, duyệt enumerator
using System;
using System.Collections;
public class Demo
{
public static void Main(string[] args)
{
SortedList sortedList = new SortedList();
sortedList.Add("A", "1");
sortedList.Add("B", "2");
sortedList.Add("C", "3");
sortedList.Add("D", "4");
sortedList.Add("E", "5");
sortedList.Add("F", "6");
sortedList.Add("G", "7");
sortedList.Add("H", "8");
sortedList.Add("I", "9");
sortedList.Add("J", "10");
Console.WriteLine("Các phần tử SortedList...");
foreach (DictionaryEntry d in sortedList)
{
Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
}
Console.WriteLine("Số cặp khóa-giá trị = " + sortedList.Count);
sortedList.RemoveAt(3); // xóa phần tử tại index 3 (D)
Console.WriteLine("\nEnumerator duyệt SortedList...");
IDictionaryEnumerator demoEnum = sortedList.GetEnumerator();
while (demoEnum.MoveNext())
Console.WriteLine("Key = " + demoEnum.Key + ", Value = " + demoEnum.Value);
Console.WriteLine("Số cặp (cập nhật) = " + sortedList.Count);
}
}
Kết quả
Các phần tử SortedList...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Số cặp khóa-giá trị = 10
Enumerator duyệt SortedList...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Số cặp (cập nhật) = 9
Chú ý
- Khóa phải implement
IComparablehoặc cung cấpIComparer. RemoveAt(index)xóa theo chỉ số (0-based) trong thứ tự đã sắp xếp.- Generic version:
SortedList<TKey, TValue>an toàn kiểu hơn.