Dev & EngARTICLE

What's New in .NET 9: The Generic Type OrderedDictionary

The OrderedDictionary class allows storing… .NET 9, from the .NET platform. However, this type had, until .NET 8.0, a major limitation…

What's New in .NET 9: The Generic Type OrderedDictionary
Image: Renato Groffe

The OrderedDictionary class allows storing keys and values while maintaining an order within a collection, having been present since the earliest versions (2.0 onward) of the .NET platform. However, this type had, until .NET 8.0, a major limitation: it was not possible to use it with Generics. Now, with .NET 9 …

.NET 9

With .NET 9 this gap has been filled, since we now have the possibility of using the generic implementation OrderedDictionary<TKey, TValue>. With this we can benefit from the ordering capability originally offered by OrderedDictionary, while also taking advantage of a stronger typing resulting from the use of Generics.

The following listing shows an example of using OrderedDictionary<TKey, TValue>:

  • The ordering of items will be respected, taking into account even the positions of each key-value pair specified during the object's initialization (lines 10 to 17);
  • The use of methods such as Add, Insert, RemoveAt and Insert (lines 18 to 21) also preserves this organization, with some of these features even allowing you to specify an index when making a change (as is the case with Insert, RemoveAt and Insert, whereas Add will add a new key-value pair at the end of the collection).
using System.Runtime.InteropServices;

Console.WriteLine("***** Testes com .NET 9 | OrderedDictionary<TKey,TValue> *****");
Console.WriteLine($"Versao do .NET em uso: {RuntimeInformation
    .FrameworkDescription} - Ambiente: {Environment.MachineName} - Kernel: {Environment
    .OSVersion.VersionString}");

Console.WriteLine();

OrderedDictionary<string, int> d = new()
{
    ["GER"] = 1974,
    ["Espanha"] = 1982,
    ["Mexico"] = 1986,
    ["Italia"] = 1990,
    ["EUA"] = 1994
};
d.Add("Franca", 1998);
d.Insert(1, "Argentina", 1978);
d.RemoveAt(0);
d.Insert(0, "Alemanha", 1974);

Console.WriteLine("Copas do Mundo de Futebol - 1974 a 1998:");
foreach (KeyValuePair<string, int> entry in d)
    Console.WriteLine(entry);

Result

The result of running this test application can be seen in the image below:

Click on this image to view it in better resolution

This project has been made available on GitHub:

https://github.com/renatogroffe/DotNet9-ConsoleApp-OrderedDictionary

If you find this solution useful, please support it with a ⭐️ on the repository. You're also invited to follow me there on GitHub!

References

Translated from the Brazilian Portuguese original · Read the original