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>
- How to convert Dictionary values into array
- How to count Dictionary items
- How to iterate over a Dictionary using foreach loop
- How to initialize a Dictionary
- How to remove first element from Dictionary
- How to remove items from Dictionary in foreach loop
- How to get key by index from a Dictionary
- How to perform foreach loop through Dictionary keys
- How to get a value by key from a Dictionary
- How to convert a Dictionary to a string