首页 文章资讯内容详情

C#中的OrderedDictionary类

2026-06-04 1 花语

OrderedDictionary类表示键/索引可访问的键/值对的集合。

以下是OrderedDictionary类的属性-

序号属性和说明1个Count

Getsthenumberofkey/valuespairscontainedin theOrderedDictionarycollection.

2IsReadOnly

获取一个值,该值指示OrderedDictionary集合是否为只读。

3Item[Int32]

Getsorsetsthevalueatthespecifiedindex.

4Item[Object]

使用指定的键获取或设置值。

5Keys

GetsanICollectionobjectcontainingthekeysin theOrderedDictionarycollection.

6

获取一个ICollection对象,该对象包含OrderedDictionary集合中的值。

以下是OrderedDictionary类的一些方法-

序号方法与说明1个Add(Object,Object)

Addsanentrywiththespecifiedkeyandvalueinto theOrderedDictionarycollectionwiththelowest availableindex.

2AsReadOnly()

返回当前OrderedDictionary集合的只读副本。

3Clear()

Removesallelementsfrom theOrderedDictionarycollection.

4Contains(Object)

确定OrderedDictionary集合是否包含特定键。

5CopyTo(Array,Int32)

CopiestheOrderedDictionaryelementstoaonedimensionalArrayobjectatthespecifiedindex.

6Equals(Object)

确定指定的对象是否等于当前的对象。(继承自Object)

7GetEnumerator()

返回一个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