c# - How to find a key by value in a Dictionary

Dictionary find key by value
dictionary-find-key-by-value.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>() {
            {10,"Sooty Tern"},
            {20,"Herring Gull"},
            {30,"Kelp Gull"},
            {40,"Black Skimmer"},
            {50,"South Polar Skua"}
        };

        Label1.Text = "dictionary keys and values..........";
        foreach (KeyValuePair<int, string> pair in birds)
        {
            Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
        }

        //get key of value 'Sooty Tern' from dictionary.
        int keyOfSootyTern = birds.FirstOrDefault(x => x.Value == "Sooty Tern").Key;

        //find key of value 'Kelp Gull' from dictionary.
        int keyOfKelpGull = birds.FirstOrDefault(x => x.Value == "Kelp Gull").Key;

        Label1.Text += "<br /><br />key of value Sooty Tern: " + keyOfSootyTern;
        Label1.Text += "<br />key of value Kelp Gull: " + keyOfKelpGull;
    }    
</script>    
    
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - dictionary find key by value</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary find key by value
        </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 find key by value"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples