C# 中的 OrderedDictionary 类
csharpserver side programmingprogramming更新于 2025/8/10 4:37:17
OrderedDictionary 类表示可通过键或索引访问的键/值对的集合。
以下是 OrderedDictionary 类的属性 −
| Sr.no | 属性 &说明 |
|---|---|
| 1 | Count 获取 OrderedDictionary 集合中包含的键/值对的数量。 |
| 2 | IsReadOnly 获取一个值,该值指示 OrderedDictionary 集合是否为只读。 |
| 3 | Item[Int32] 获取或设置指定索引处的值。 |
| 4 | Item[Object] 获取或设置具有指定键的值。 |
| 5 | Keys 获取一个包含 OrderedDictionary 集合中键的 ICollection 对象。 |
| 6 | Values 获取一个包含 OrderedDictionary 集合中值的 ICollection 对象。 |
以下是 OrderedDictionary 类的一些方法 −
| Sr.no | 方法 &说明 |
|---|---|
| 1 | Add(Object, Object) 将具有指定键和值的条目添加到 OrderedDictionary 集合中,该集合具有最低的可用索引。 |
| 2 | AsReadOnly() 返回当前 OrderedDictionary 集合的只读副本。 |
| 3 | Clear() 从 OrderedDictionary 集合中删除所有元素。 |
| 4 | Contains(Object) 确定 OrderedDictionary 集合是否包含特定键。 |
| 5 | CopyTo(Array, Int32) 将 OrderedDictionary 元素复制到指定索引处的一维 Array 对象。 |
| 6 | Equals(Object) 判断指定对象是否等于当前对象。 (继承自 Object) |
| 7 | GetEnumerator() 返回一个 IDictionaryEnumerator 对象,用于迭代 OrderedDictionary 集合。 |
现在来看一些示例 −
示例
要获取 OrderedDictionary 中包含的键/值对的数量,代码如下 −
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Home Appliances");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.Clear();
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}
输出
这将产生以下输出 −
OrderedDictionary elements... A Home Appliances B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated)= 0
示例
从OrderedDictionary中移除所有元素,代码如下 −
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
OrderedDictionary dict = new OrderedDictionary();
dict.Add("A", "Books");
dict.Add("B", "Electronics");
dict.Add("C", "Smart Wearables");
dict.Add("D", "Pet Supplies");
dict.Add("E", "Clothing");
dict.Add("F", "Footwear");
Console.WriteLine("OrderedDictionary elements...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Count of elements in OrderedDictionary = " + dict.Count);
dict.Clear();
Console.WriteLine("Count of elements in OrderedDictionary (Updated)= " + dict.Count);
}
}
输出
这将产生以下输出 −
OrderedDictionary elements... A Books B Electronics C Smart Wearables D Pet Supplies E Clothing F Footwear Count of elements in OrderedDictionary = 6 Count of elements in OrderedDictionary (Updated)= 0

