C#中的OrderedDictionary类
OrderedDictionary类表示键/索引可访问的键/值对的集合。
以下是OrderedDictionary类的属性-
Count
Getsthenumberofkey/valuespairscontainedin
theOrderedDictionarycollection.
获取一个值,该值指示OrderedDictionary集合是否为只读。
Item[Int32]
Getsorsetsthevalueatthespecifiedindex.
使用指定的键获取或设置值。
Keys
GetsanICollectionobjectcontainingthekeysin
theOrderedDictionarycollection.
获取一个ICollection对象,该对象包含OrderedDictionary集合中的值。
以下是OrderedDictionary类的一些方法-
Add(Object,Object)
Addsanentrywiththespecifiedkeyandvalueinto
theOrderedDictionarycollectionwiththelowest
availableindex.
返回当前OrderedDictionary集合的只读副本。
Clear()
Removesallelementsfrom
theOrderedDictionarycollection.
确定OrderedDictionary集合是否包含特定键。
CopyTo(Array,Int32)
CopiestheOrderedDictionaryelementstoaonedimensionalArrayobjectatthespecifiedindex.
确定指定的对象是否等于当前的对象。(继承自Object)
返回一个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