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:
Countis a property, not a method. Writescores.Countwith no parentheses.scores.Count()is a different thing: it calls a LINQ method, and it only compiles whenusing System.Linq;is present. Code ported from Java often usessize(), which doesn't exist in C#.- It counts pairs, not keys plus values. The dictionary above has three entries, so
Countis 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:
| Type | Size |
|---|---|
int[] (array) | Length |
string | Length |
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.
- Declare an
intvariable namedcountbelow the dictionary. - Assign it the dictionary's
Countproperty, without parentheses. The dictionary has three keys, socountbecomes 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. Withoutusing System.Linq;this fails to compile. With it, the code compiles but runs a LINQ method where the property would do. - Using
Lengthorsize(). A dictionary has neither.Lengthis for arrays and strings. - Reading
Counttoo early. The value is the count at the moment you read it. A variable such ascountdoesn't update when you add entries later. - Expecting duplicates to count. Assigning to the same key twice makes one entry, so
Countstays at 1.
Key takeaways
dictionary.Countis 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 useCount.