Dictionary union
dictionary-union.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,"Caspian Tern"},
{2,"Plain Chachalaca"}
};
Dictionary<int, string> birds2 = new Dictionary<int, string>() {
{2,"Greater Rhea"},
{3,"Little Tinamou"}
};
Label1.Text = "dictionary keys and values..........";
foreach (KeyValuePair<int, string> pair in birds)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
Label1.Text += "<br /><br />dictionary2 keys and values..........";
foreach (KeyValuePair<int, string> pair in birds2)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
//keep all elements from birds dictionary.
Dictionary<int, string> result = birds;
foreach (KeyValuePair<int, string> pair in birds2)
{
//this line check for duplicate keys.
if (result.ContainsKey(pair.Key) == false)
{
//only unique key added in marged dictionary.
result.Add(pair.Key,pair.Value);
}
}
Label1.Text += "<br /><br />dictionary union [keep all from dictionary1]..........";
foreach (KeyValuePair<int, string> pair in result)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
//keep all elements from birds2 dictionary.
Dictionary<int, string> result2 = birds2;
foreach (KeyValuePair<int, string> pair in birds)
{
//this line check for duplicate keys.
if (result2.ContainsKey(pair.Key) == false)
{
//only unique key added in marged dictionary.
result2.Add(pair.Key, pair.Value);
}
}
Label1.Text += "<br /><br />dictionary union [keep all from dictionary2]..........";
foreach (KeyValuePair<int, string> pair in result2)
{
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 union</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - dictionary union
</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 union"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>

- How to iterate over a Dictionary using foreach loop
- How to sort a Dictionary by key
- How to sort a Dictionary by value
- How to remove first element from Dictionary
- How to remove items from Dictionary in foreach loop
- How to get a key value pair from Dictionary
- How to get first key value from Dictionary
- How to merge two Dictionaries
- How to reverse a Dictionary items
- How to convert a Dictionary to a string