c# - How to count Dictionary items

Dictionary Count Property
.Net framework Dictionary<TKey, TValue>.Count property allow us to get the number of key/value pairs contained in the Dictionary<TKey, TValue>. the dictionary Count property exists under System.Collections.Generic namespace.

Dictionary<TKey, TValue>.Count property value data type is System.Int32. this integer value represents the number of key/value pairs contained in the Dictionary<TKey, TValue>. a single key and value pair represent an element of dictionary. so by using the Count property we can get the number of elements contained in the dictionary.

the dictionary Count property implements as ICollection<T>.Count, ICollection.Count and IReadOnlyCollection<T>.Count. dictionary Count property return the number of elements that are actually exists in the Dictionary<TKey, TValue>.

the following asp.net c# example code demonstrate us how can we get the number of elements contained in the dictionary in an asp.net application.
CountDictionaryKeyValuePairs.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("DarkCyan", "#008B8B");
        colors.Add("FireBrick", "#B22222");
        colors.Add("GoldenRod", "#DAA520");
        colors.Add("Indigo", "#4B0082");
        colors.Add("MediumVioletRed", "#C71585");

        Label1.Text = "Number of key/value pairs exists in Dictionary: " + colors.Count;
        Label1.Text += "<br /><br /><u>Dictionary Keys</u>.....<br />";
        foreach (string color in colors.Keys)
        {
            Label1.Text +="<font color="+color+">" + color + "</font><br />";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Dictionary Count - How to get the number of key value pairs contained in the Dictionary</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy; font-style:italic;">
            System.Collections.Generic.Dictionary Count Property
            <br /> How to get the number of key/value pairs contained in the Dictionary
        </h2>
        <hr width="700" align="left" color="Navy" />
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Navy"
             Font-Names="Courier New"
             Font-Size="Large"
             >
        </asp:Label>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Count Dictionary Key/Value Pairs"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>
More c# examples