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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {10,"Southern Lapwing"}, {20,"Eurasian Golden Plover"}, {30,"Grey Plover"}, {40,"Ringed Plover"}, {50,"Kentish Plover"} }; Console.WriteLine("dictionary elements with index.........."); for (int i = 0; i < birds.Count; i++) { Console.WriteLine("index: " + i+" key: " + birds.ElementAt(i).Key+" value: " + birds.ElementAt(i).Value); } //get key of dictionary element by index. int keyOfIndex1 = birds.ElementAt(1).Key; //get key of dictionary index 3 element. int keyOfIndex3 = birds.ElementAt(3).Key; Console.WriteLine("\nkey of dictionary element at index 1: " + keyOfIndex1); Console.WriteLine("\nkey of dictionary element at index 3: " + keyOfIndex3); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
dictionary elements with index.......... index: 0 key: 10 value: Southern Lapwing index: 1 key: 20 value: Eurasian Golden Plover index: 2 key: 30 value: Grey Plover index: 3 key: 40 value: Ringed Plover index: 4 key: 50 value: Kentish Plover key of dictionary element at index 1: 20 key of dictionary element at index 3: 40 |