To get the size (number of key-value pairs) of a dictionary in C#, you can use the `Count` property of the `Dictionary
We can get the size of a dictionary in C# using the `Count` property. This example demonstrates how to declare and initialize a dictionary, use the `Count` property to get the number of key-value pairs, and print the size.
For example,
using System.Collections.Generic;
.myDictionary
with integer keys and string values.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize a dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>
{
{1, "One"},
{2, "Two"},
{3, "Three"}
};
// Get the size of the dictionary using the Count property
int size = myDictionary.Count;
// Print the size of the dictionary
Console.WriteLine("The size of the dictionary is {0}.", size);
}
}
The size of the dictionary is 3.
We can get the size of an empty dictionary in C# using the `Count` property. This example demonstrates how to declare and initialize an empty dictionary, use the `Count` property to get the number of key-value pairs, and print the size.
For example,
using System.Collections.Generic;
.myDictionary
.using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Declare and initialize an empty dictionary
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
// Get the size of the dictionary using the Count property
int size = myDictionary.Count;
// Print the size of the dictionary
Console.WriteLine("The size of the dictionary is {0}.", size);
}
}
The size of the dictionary is 0.
In this tutorial, we learned How to Get the Size (Number of Key-Value Pairs) of a Dictionary in C# language with well detailed examples.