OrderedDictionary Class
Provides a collection of key/value pairs that are accessible by index or by key.
Namespace
System.Collections.Specialized
Assembly
System.Collections.Specialized.dll
Syntax
C#
public class OrderedDictionary : IDictionary, ICollection, IEnumerable, IDictionary<object, object>, ICollection<KeyValuePair<object, object>>, IEnumerable<KeyValuePair<object, object>>, ISerializable, IDeserializationCallback
Constructors
Signature | Description |
---|---|
OrderedDictionary() | Initializes a new instance of the OrderedDictionary class that is empty, has the default initial capacity, and uses the default IEqualityComparer . |
OrderedDictionary(int capacity) | Initializes a new instance with the specified capacity. |
OrderedDictionary(IEqualityComparer comparer) | Initializes a new instance that uses the specified comparer. |
OrderedDictionary(int capacity, IEqualityComparer comparer) | Initializes a new instance with the specified capacity and comparer. |
Properties
Name | Type | Description |
---|---|---|
Count | int | Gets the number of elements. |
IsReadOnly | bool | Gets a value indicating whether the dictionary is read‑only. |
IsFixedSize | bool | Gets a value indicating whether the dictionary has a fixed size. |
Keys | ICollection | Gets an ICollection of the keys. |
Values | ICollection | Gets an ICollection of the values. |
this[int index] | object | Gets or sets the value at the specified index. |
this[object key] | object | Gets or sets the value with the specified key. |
Methods
Name | Signature | Description |
---|---|---|
Add | void Add(object key, object value) | Adds an entry with the specified key and value. |
Clear | void Clear() | Removes all entries. |
Contains | bool Contains(object key) | Determines whether the dictionary contains the specified key. |
ContainsKey | bool ContainsKey(object key) | Same as Contains . |
ContainsValue | bool ContainsValue(object value) | Determines whether the dictionary contains a specific value. |
GetEnumerator | IDictionaryEnumerator GetEnumerator() | Returns an enumerator that iterates through the collection. |
Insert | void Insert(int index, object key, object value) | Inserts a new entry at the specified index. |
Remove | void Remove(object key) | Removes the entry with the specified key. |
RemoveAt | void RemoveAt(int index) | Removes the entry at the specified index. |
Example
C#
// Create an OrderedDictionary and add some items
OrderedDictionary od = new OrderedDictionary();
od.Add("first", 1);
od.Add("second", 2);
od.Add("third", 3);
// Access by key
Console.WriteLine(od["second"]); // Output: 2
// Access by index
Console.WriteLine(od[0]); // Output: 1
// Insert at a specific position
od.Insert(1, "inserted", 99);
// od now: first, inserted, second, third
// Enumerate
foreach (DictionaryEntry entry in od)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}