c# - How to remove all items from a Dictionary

Dictionary Clear() Method
.Net framework dictionary Clear() method allow us to remove all keys and values from the Dictionary<TKey, TValue>. this Dictionary<TKey, TValue>.Clear() method exists under System.Collections.Generic namespace. this method has no optional or required parameter.

the Clear() method implements as ICollection<T>.Clear() and IDictionary.Clear(). this method set the Count property value to 0 (zero) but the Capacity remains unchanged.

the following asp.net c# example code demonstrate us how can we remove all elements from dictionary programmatically at run time in an asp.net application.
DictionaryClearMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Dictionary<string, string> colors = new Dictionary<string, string>();
        colors.Add("BlanchedAlmond", "#FFEBCD");
        colors.Add("Brown", "#A52A2A");
        colors.Add("Cornsilk", "#FFF8DC");
        colors.Add("FireBrick", "#B22222");
        colors.Add("GreenYellow", "#ADFF2F");

        Label1.Text = "Dictionary Keys...<br />";

        foreach (string color in colors.Keys)
        {
            Label1.Text += color + "<br />";
        }

        //Clear() method remove all keys and values from the Dictionary.
        colors.Clear();
        Label1.Text += "<br />After Call Clear() Method. Dictionary Keys...<br />";

        foreach (string color in colors.Keys)
        {
            Label1.Text += color + "<br />";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Dictionary Clear() Method - How to remove all keys and values from the Dictionary</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">
            System.Collections.Generic.Dictionary Clear() Method
            <br /> How to remove all keys and values from the Dictionary
        </h2>
        <hr width="550" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="SeaGreen"
             Font-Names="Courier New"
             Font-Size="Large"
             >
        </asp:Label>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test Dictionary Clear() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>
More c# examples