Dictionary add if not exists
dictionary-add-if-not-exists.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,"Greater Flamingo"},
{2,"Andean Flamingo"}
};
Label1.Text = "dictionary keys and values..........";
foreach (KeyValuePair<int, string> pair in birds)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
//create new keyvaluepair
KeyValuePair<int, string> pair1 = new KeyValuePair<int, string>(1, "Wood Stork");
KeyValuePair<int, string> pair2 = new KeyValuePair<int, string>(3, "African Openbill");
//add keyvaluepair to dictionary if key is not exists in dictionary.
if (birds.ContainsKey(pair1.Key) == false)
{
birds.Add(pair1.Key, pair1.Value);
}
//add another keyvaluepair to dictionary if key is not exists in dictionary.
if (birds.ContainsKey(pair2.Key) == false)
{
birds.Add(pair2.Key, pair2.Value);
}
Label1.Text += "<br /><br />dictionary elements after added new..........";
foreach (KeyValuePair<int, string> pair in birds)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>c# example - dictionary add if not exists</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - dictionary add if not exists
</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 add if not exists"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>
- How to add an item to a Dictionary
- How to remove all items from a Dictionary
- How to check whether Dictionary contains a specific key
- How to check whether Dictionary contains a specific value
- How to update a value in a Dictionary
- How to update a key in a Dictionary
- How to access Dictionary items
- How to iterate through a Dictionary using for loop
- How to reverse a Dictionary items
- How to convert a Dictionary to a string