.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 c# example code demonstrate us how can we get the number of elements contained in the dictionary in an application.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Program { static void Main(string[] args) { Dictionary<string, ConsoleColor> colors = new Dictionary<string, ConsoleColor>(); colors.Add("Blue", ConsoleColor.Blue); colors.Add("Green", ConsoleColor.Green); colors.Add("Magenta", ConsoleColor.Magenta); colors.Add("White", ConsoleColor.White); colors.Add("Yellow", ConsoleColor.Yellow); Console.WriteLine("Number of key/value pairs exists in Dictionary: " + colors.Count); Console.WriteLine("\n\nDictionary Values....."); foreach (ConsoleColor color in colors.Values) { Console.ForegroundColor = color; Console.WriteLine( color ); } Console.ReadLine(); } } |
Output: