Author : Admin
Last Modified : 07-Dec-2019
Complexity : Beginner

How to find the index of key in dictionary


In the .Net framework, the dictionary is the collection of keys and values. and each element is the combination of key and value (Dictionary < key, value> ). the key is unique in the Dictionary so we can use Linq to find the index of the intended key. So first we fetch the List of keys the Dictionary and use IndexOf() method to the result List for finding the Index of the key. and both operation can be done in inline with the help of Linq.

below code demonstrate, how you find the index of a key?

            Dictionary dicEmployee = new Dictionary();
            dicEmployee.Add("Red", "Red");
            dicEmployee.Add("Orange", "Orange");
            dicEmployee.Add("Black", "Black");
            dicEmployee.Add("White", "White");
            dicEmployee.Add("Yellow", "Yellow");
            var index = dicEmployee.Keys.ToList().IndexOf("Black");
                
Output : 2