OrderedDictionary类表示键/索引可访问的键/值对的集合。
以下是OrderedDictionary类的属性-
序号 | 属性和说明 |
---|---|
1个 | Count |
2 | IsReadOnly 获取一个值,该值指示OrderedDictionary集合是否为只读。 |
3 | Item[Int32] |
4 | Item [Object] 使用指定的键获取或设置值。 |
5 | Keys |
6 | 值 获取一个ICollection对象,该对象包含OrderedDictionary集合中的值。 |
以下是OrderedDictionary类的一些方法-
序号 | 方法与说明 |
---|---|
1个 | Add(Object, Object) |
2 | AsReadOnly() 返回当前OrderedDictionary集合的只读副本。 |
3 | Clear() |
4 | Contains(Object) 确定OrderedDictionary集合是否包含特定键。 |
5 | CopyTo(Array, Int32) |
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