Dictionary remove in for loop
dictionary-remove-in-loop.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,"Topknot Pigeon"},
{2,"Mourning Dove"},
{3,"Kakapo"},
{4,"Rainbow Lorikeet"},
{5,"Varied Lorikeet"}
};
Label1.Text = "dictionary keys and values..........";
foreach (KeyValuePair<int , string> pair in birds)
{
Label1.Text += "<br />" + pair.Key + " ........ " + pair.Value;
}
//create an int array with dictionary keys which are >=3.
int[] keys = birds.Keys.Where(x => x>=3).ToArray();
Label1.Text += "<br /><br />removing keys from dictionary which key>=3<br />";
for (int i = 0; i < keys.Count(); i++)
{
//remove element from dictionary.
birds.Remove(keys[i]);
Label1.Text += "key [" + keys[i] + "] removed from dictionary<br />";
}
Label1.Text += "<br />dictionary keys and values after removing elements..........";
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 remove in loop</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
c# example - dictionary remove in loop
</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 remove in loop"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>

- How to remove first element from Dictionary
- How to remove items from Dictionary in foreach loop
- How to remove items from a Dictionary while iterating
- How to get a value by key from a Dictionary
- How to find a key by value in a Dictionary
- How to merge two Dictionaries
- How to union two Dictionaries
- How to update a value in a Dictionary
- How to update a key in a Dictionary
- How to access Dictionary items