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

SignatureDescription
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

NameTypeDescription
CountintGets the number of elements.
IsReadOnlyboolGets a value indicating whether the dictionary is read‑only.
IsFixedSizeboolGets a value indicating whether the dictionary has a fixed size.
KeysICollectionGets an ICollection of the keys.
ValuesICollectionGets an ICollection of the values.
this[int index]objectGets or sets the value at the specified index.
this[object key]objectGets or sets the value with the specified key.

Methods

NameSignatureDescription
Addvoid Add(object key, object value)Adds an entry with the specified key and value.
Clearvoid Clear()Removes all entries.
Containsbool Contains(object key)Determines whether the dictionary contains the specified key.
ContainsKeybool ContainsKey(object key)Same as Contains.
ContainsValuebool ContainsValue(object value)Determines whether the dictionary contains a specific value.
GetEnumeratorIDictionaryEnumerator GetEnumerator()Returns an enumerator that iterates through the collection.
Insertvoid Insert(int index, object key, object value)Inserts a new entry at the specified index.
Removevoid Remove(object key)Removes the entry with the specified key.
RemoveAtvoid 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}");
}

See Also