c# - How to remove items from a Dictionary by condition

Dictionary remove by condition
dictionary-remove-where.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,"Squirrel Cuckoo"},
            {2,"Golden Oriole"},
            {3,"Golden Nightjar"},
            {4,"Northern Oriole"},
            {5,"Warbling Vireo"}
        };

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

        int[] keysToDelete = birds.Where(x => x.Value.EndsWith("Oriole")).Select(x => x.Key).ToArray();

        //another condition to remove dictionary elements.
        //int[] keysToDelete = birds.Keys.Where(x => x < 3).ToArray();

        Label1.Text += "<br /><br />removing elements from dictionary<br />";

        foreach (int key in keysToDelete)
        {
            birds.Remove(key);
            Label1.Text += "key [" + key + "] removed from dictionary<br />";
        }

        Label1.Text += "<br />elemetns removed which value ends with [Oriole]..........";
        Label1.Text += "<br />dictionary keys and values after remove..........";
        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 where</title>    
</head>    
<body>    
    <form id="form1" runat="server">    
    <div>    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - dictionary remove where
        </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 where"    
            OnClick="Button1_Click"  
            Height="40"    
            Font-Bold="true"    
            />    
    </div>    
    </form>    
</body>    
</html>
More c# examples