.NET 9 — OrderedDictionary<TKey, TValue>
The OrderedDictionary class represents a collection of key-value pairs that are accessible by the key or index, and allows you to store the elements in a way that preserves their order.
This class has been available in earlier versions of .NET, but it only supported non-generic implementations. With .NET 9, the OrderedDictionary<TKey, TValue>
class was introduced, and now allows you to store key-value pairs in an ordered manner while providing support for Generics.
When using the OrderedDictionary<TKey, TValue>
collection, whenever you add or remove an item, the existing order of the elements is maintained. This characteristic allows you to retrieve items in the sequence they were added, making it ideal for scenarios where the order of operations matters.
In the code below you can see an example of using this class:
- On line 1, a new collection is being created with three elements
- On line 8, a new element is added, and it will be added at the end of the collection
- On line 10, the first element in the collection is removed
- On line 12, a new element is added as the first element of the collection
- On line 14, the collection is displayed
The output is:
Step 1: Preheat the oven to 180°C
Step 2: Mix flour and sugar
Step 3: Add eggs and stir well
Step 4: Bake for 25 minutes
Conclusion
The OrderedDictionary<Tkey, TValue>
is an efficient and type-safe way to store Generics key-values types in the order they are added, enables you to organize items sequentially. This can be used in situations where order and efficient access are both essential, like ordered collections that are frequently accessed by key.
This is the link for the project in GitHub: https://github.com/henriquesd/OrderedDictionaryDotNet9
If you like this demo, I kindly ask you to give a ⭐️ in the repository.
Thanks for reading!