C# 中的 OrderedDictionary 类
OrderedDictionary 类表示一个键/值对的集合,可以通过键或索引访问。
以下是 OrderedDictionary 类的属性:
| 序号 | 属性 & 描述 |
|---|---|
| 1 | Count 获取 OrderedDictionary 集合中包含的键/值对的数量。 |
| 2 | IsReadOnly 获取一个值,指示 OrderedDictionary 集合是否为只读。 |
| 3 | Item[Int32] 获取或设置指定索引处的 value。 |
| 4 | Item[Object] 获取或设置指定键的 value。 |
| 5 | Keys 获取一个包含 OrderedDictionary 集合中键的 ICollection 对象。 |
| 6 | Values 获取一个包含 OrderedDictionary 集合中值的 ICollection 对象。 |
以下是 OrderedDictionary 类的一些方法:
| 序号 | 方法 & 描述 |
|---|---|
| 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 是否等于当前 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP