C# C# Console Application

How to get key by index from a Dictionary in C#2 min read

How to get item by index from a Dictionary in C#

Net framework dictionary represents a collection of keys and values. each element of dictionary contain a key and value pair. so to get the dictionary key by index, first we need to find the specified element by index and then get this element’s key.




Enumerable.ElementAt<TSource> method allow us to get the element at a specified index in a sequence. this method exists in System.Linq namespace. this method type parameter is ‘TSource’ which represents type of the elements of ‘source’. ElementAt() method require to pass two parameters named ‘source’ and ‘index’.

‘source’ parameter type is System.Collections.Generic.IEnumerable<TSource> which represents an IEnumerable<T> to return an element from. ‘index’ parameter value data type is System.Int32 which represents the zero based index of the element to retrieve.

this method throw ArgumentNullException exception, if the ‘source’ is null. method also throw ArgumentOutOfRangeException exception, if the ‘index’ is less than zero or greater than or equal to the number of elements in ‘source’.

Enumerable.ElementAt<TSource> method return value type is ‘TSource’ which represents the element at the specified index position of the source sequence. so by using this method we can get an element of dictionary from a specified index. after retrieving the element we can get its ‘Key’ by accessing Pair.Key. finally the process is Dictionary<TKey, TValue>.ElementAt(index).Key.

the following  c# example code demonstrate us how can we get dictionary key by index programmatically at run time in an console application.

C# Code:

 

Output:

 

Leave a Comment