In this article, we’re going to explore accessing Dictionary items by index in C# and its performance considerations.

The Dictionary<TKey,TValue> generic class provides the ability to map keys to values. Retrieving a value by using its key is quite fast, almost O(1) thanks to the implementation of Dictionary<TKey, TValue> class as a hash table.

Every element of Dictionary is a key-value pair. 

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

While it is optimum to access elements via the key, sometimes we need to access Dictionary items by index. Let’s see how to do that.

To download the source code for this article, you can visit our GitHub repository.

Ready? Let’s get started.

Creating a Dictionary

For accessing elements via index, first, we need to create a Dictionary<string, string> object:

var capitals = new Dictionary<string, string>()
{
    {"Turkey", "Ankara"},
    {"UK", "London"},
    {"USA", "Washington"}                
};

Nothing special here, just a Dictionary<string, string> object that contains three key-value pairs that we can play with. It uses the country name as the key and the country capital as the value.

Access Dictionary Elements Using Index 

When we want to access an element using the index, we are going to use the ElementAt method:

var element = capitals.ElementAt(2);

The ElementAt method  provides us array-like access capability to key-value pairs of  Dictionary<string, string>

As with C# arrays, the index of the first element is 0. 

So if we type ElementAt(2) we get the value of the third key-value pair of our Dictionary:

[Usa, Washington]

We can even access the key or value of certain elements individually:

Console.WriteLine($"Just Key: {capitals.ElementAt(2).Key}");

Console.WriteLine($"Just Value: {capitals.ElementAt(2).Value}");

If we start our application and test this implementation, we can see that everything works as expected:

[USA, Washington]
Just Key: USA
Just Value: Washington

Performance Considerations While Using Index  

The Dictionary<TKey,TValue> is designed for holding key-value pairs so it is not reasonable to use it with arrays in mind. Yeah, there is an Array class in .NET we can use for such scenarios. So using The Dictionary<TKey,TValue> as an array has a performance penalty. 

The Dictionary<TKey,TValue> has no way to access directly the nth “element” via ElementAt. If we want to access the nth “element”, the Dictionary needs to enumerate all of the entries in it.  Performance is O(n) and the performance penalty increases with the size of the dictionary.

So each call to the ElementAt method takes time and hence we should use it wisely.

Difference Between Indexer and Access by Index

Sometimes there’s confusion about the usage of the indexer and index access.

The indexer uses TKey of Dictionary<TKey,TValue> to access the value:

Console.WriteLine($"This is the indexer access of the UK capital: {capitals["UK"]}");

Using brackets does not mean we use index value, we used just TKey value of dictionary:

This is indexer access of UK capital: London

Conclusion

As we can see, accessing Dictionary elements via an index is easy, but we have to consider the performance penalties, especially with Dictionaries that have many elements.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!