Count
, Dictionary
A Dictionary
contains a certain number of keys and values. This number is returned by the Count
property. No looping is usually needed.
With Count
we quickly determine how much data is stored in the Dictionary
. The field is stored as elements are added, so it is fast to access.
The Count
property returns the number of keys. This count integer is not equal to the Dictionary
fill rate or its internal bucket count.
Count
returns the exact number of key-value pairs you have added (and have not removed).Dictionary
. Its count at this point is equal to 4.Dictionary
is cleared, which puts its count at zero. The Count
property is readonly
.using System; using System.Collections.Generic; // Create new Dictionary with 4 keys. Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("carrot", 1); dictionary.Add("pear", 4); dictionary.Add("apple", 6); dictionary.Add("kiwi", 3); // Count the keys. int count1 = dictionary.Count; // Remove one key. dictionary.Remove("pear"); // Count the keys again. int count2 = dictionary.Count; // Clear the Dictionary contents. dictionary.Clear(); // Count the keys again. int count3 = dictionary.Count; // Write the counts of the Dictionary. Console.WriteLine(count1); Console.WriteLine(count2); Console.WriteLine(count3);4 3 0
Count
is implemented as a property accessor—it is not a direct field access. Instead, the call to Count
does a simple and fast calculation each time you call it.
freeCount
" field is subtracted from the "count" field, resulting in one "sub" IL instruction.public int Count { get { return (this.count - this.freeCount); } }
The Count
property gives you no insight into the internal implementation state of the Dictionary
. For detailed performance analysis, a debugger can be used.
Dictionary
has many fields, such as a "buckets" field, along with freeList
and freeCount
fields.The Count
property cannot be used to filter or selectively count keys. For this purpose, we can use a foreach
-loop over the Keys
property, with an if
-conditional.
Count()
extension, from the System.Linq
namespace, typically has much worse performance.We can get the number of keys and values in a Dictionary
. Because the Dictionary
enforces unique keys, you can use Count
to compute the number of unique keys in a collection.