Start learning free

LESSON 103 OF 347 · DICTIONARIES

Dictionary Length in C#: The Count Property

Lesson Read the full explanation

In Java, you can get the number of key-value pairs in a HashMap using the size() method:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Charlie"] = 72;

int count = scores.Count;
Console.WriteLine(count);  // 3

size() returns the number of entries. You can also check if it's empty with isEmpty():

Console.WriteLine(scores.Count == 0);  // False
Dictionary<string, int> empty = new Dictionary<string, int>();
Console.WriteLine(empty.Count);        // 0

Assignment
Follow the Coding Tutorial and get the number of entries in scores!


Hint
Use scores.size() and assign it to count.

STEP 1 OF 1
    Ctrl + Enter to check

    C# · DICTIONARIES

    Dictionary Length in C#, explained

    Counting entries

    The size of a Dictionary<TKey, TValue> is the number of key-value pairs it holds. C# exposes it as the Count property:

    Dictionary<string, int> scores = new Dictionary<string, int>();
    scores["Alice"] = 95;
    scores["Bob"] = 87;
    scores["Charlie"] = 72;
    
    int count = scores.Count;
    Console.WriteLine(count);  // 3
    

    Three details matter here:

    • Count is a property, not a method. Write scores.Count with no parentheses. scores.Count() is a different thing: it calls a LINQ method, and it only compiles when using System.Linq; is present. Code ported from Java often uses size(), which doesn't exist in C#.
    • It counts pairs, not keys plus values. The dictionary above has three entries, so Count is 3, not 6.
    • It is cheap. The dictionary keeps the count up to date, so reading it takes constant time no matter how large the dictionary is.

    How Count changes

    Count follows what you do to the dictionary:

    var d = new Dictionary<string, int>();
    Console.WriteLine(d.Count);   // 0
    
    d["a"] = 1;
    d["b"] = 2;
    Console.WriteLine(d.Count);   // 2
    
    d["a"] = 10;                  // existing key: replaces the value
    Console.WriteLine(d.Count);   // 2
    
    d.Remove("b");
    Console.WriteLine(d.Count);   // 1
    
    d.Clear();
    Console.WriteLine(d.Count);   // 0
    

    Only new keys increase the count. Replacing a value for an existing key leaves it unchanged, since keys are unique. Remove lowers it when the key was present, and Clear resets it to 0.

    Checking for an empty dictionary

    C# has no isEmpty() method on dictionaries. Compare the count with zero instead:

    Console.WriteLine(scores.Count == 0);  // False
    
    Dictionary<string, int> empty = new Dictionary<string, int>();
    Console.WriteLine(empty.Count);        // 0
    Console.WriteLine(empty.Count == 0);   // True
    

    Notice that Console.WriteLine prints a bool as True or False, with a capital first letter.

    What counts as a different key

    Because Count is the number of distinct keys, it depends on how keys are compared. String keys are compared by their characters, case included:

    var names = new Dictionary<string, int>();
    names["Ann"] = 1;
    names["Ann"] = 2;   // same key
    names["ann"] = 3;   // different key: the case differs
    
    Console.WriteLine(names.Count);  // 2
    

    Assigning to "Ann" twice produced one entry, but "ann" is a separate key and adds a second. If a count looks larger than you expect, look for keys that differ only in case or in stray spaces.

    Using Count in practice

    The count is useful whenever the number of entries drives a decision. A few typical uses:

    if (scores.Count == 0) {
        Console.WriteLine("No scores yet");
    }
    
    double total = 0;
    foreach (var pair in scores) {
        total += pair.Value;
    }
    double average = total / scores.Count;
    

    The average divides by Count. Check for an empty dictionary first when that can happen, because for an empty dictionary the total is 0, and 0.0 divided by 0 gives NaN (not a number) instead of a useful average. If total were an int, total / scores.Count would be integer division and drop the fraction.

    The Keys and Values collections have their own Count, and both equal the dictionary's. Counting entries never needs a loop.

    Count is not an index

    Dictionaries have no positions, so Count says how many entries exist but doesn't give you a way to reach "the last one". You reach entries by key, or by looping over all of them. This is the main difference from a list, where Count - 1 is the index of the last item.

    Count, Length and the others

    Different collections name their size differently, which is easy to mix up:

    TypeSize
    int[] (array)Length
    stringLength
    List<T>Count
    Dictionary<TKey, TValue>Count

    The exercise, step by step

    The lesson starts with a scores dictionary that holds three students, and asks for the number of entries.

    1. Declare an int variable named count below the dictionary.
    2. Assign it the dictionary's Count property, without parentheses. The dictionary has three keys, so count becomes 3.
            Dictionary<string, int> scores = new Dictionary<string, int>();
            scores["Alice"] = 95;
            scores["Bob"] = 87;
            scores["Charlie"] = 72;
    
            int count = scores.Count;
    

    Common mistakes

    • Writing Count() with parentheses. Without using System.Linq; this fails to compile. With it, the code compiles but runs a LINQ method where the property would do.
    • Using Length or size(). A dictionary has neither. Length is for arrays and strings.
    • Reading Count too early. The value is the count at the moment you read it. A variable such as count doesn't update when you add entries later.
    • Expecting duplicates to count. Assigning to the same key twice makes one entry, so Count stays at 1.

    Key takeaways

    • dictionary.Count is the number of key-value pairs.
    • It is a property: no parentheses.
    • Test for emptiness with Count == 0.
    • Arrays and strings use Length; lists and dictionaries use Count.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free