C# 中的 SortedList 类是什么?
csharpprogrammingserver side programming更新于 2025/10/13 17:22:17
排序列表是数组和哈希表的组合。它包含一个可以使用键或索引访问的项目列表。如果使用索引访问项目,则它是一个 ArrayList;如果使用键访问项目,则它是一个 Hashtable。项目集合始终按键值排序。
让我们看一个例子,其中我们为 SortedList 添加了 4 个键值对 −
示例
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
SortedList s = new SortedList();
s.Add("S1", "Maths");
s.Add("S2", "Science");
s.Add("S3", "English");
s.Add("S4", "Economics");
}
}
}
现在让我们看看如何获取 SortedList 的键并显示它 −
示例
using System;
using System.Collections;
namespace Demo {
class Program {
static void Main(string[] args) {
SortedList sl = new SortedList();
sl.Add("ST0", "One");
sl.Add("ST1", "Two");
sl.Add("ST2", "Three");
sl.Add("ST3", "Four");
sl.Add("ST4", "Five");
sl.Add("ST5", "Six");
sl.Add("ST6", "Seven");
ICollection key = sl.Keys;
foreach (string k in key) {
Console.WriteLine(k);
}
}
}
}

