c# - How to get index of an item by key from a Dictionary

Dictionary get index of a key
dictionary-index-of-key.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>
  
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        //initialize a dictionary with keys and values.
        Dictionary<int, string> birds = new Dictionary<int, string>() {
            {1,"Banded Stilt"},
            {2,"Pied Avocet"},
            {3,"Blacksmith Plover"},
            {4,"Northern Lapwing"},
            {5,"Masked Lapwing"}
        };

        Label1.Text = "dictionary elements with index..........";
        for (int i = 0; i < birds.Count; i++)
        {
            Label1.Text += "<br />" + "index: " + i;
            Label1.Text += " key: " + birds.ElementAt(i).Key;
            Label1.Text += " value: " + birds.ElementAt(i).Value;
        }
        
        //find index of dictionary elements by key.
        int index = birds.Keys.ToList().IndexOf(3);

        Label1.Text += "<br /><br />index of key [3] is: " + index;
        
        //another way to find index of dictionary elements by key.
        for (int i = 0; i < birds.Count;i++ )
        {
            if (birds.ElementAt(i).Key == 4)
            {
                Label1.Text += "<br />index of key [4] is: " + i;
            }
        }
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary index of key</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary index of key
        </h2>    
        <hr width="550" align="left" color="Gainsboro" />    
        <asp:Label     
            ID="Label1"     
            runat="server"    
            Font-Size="Large"  
            >    
        </asp:Label>    
        <br /><br />  
        <asp:Button     
            ID="Button1"     
            runat="server"     
            Text="dictionary index of key"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples