To clear all key-value pairs from a dictionary in C#, you can use the `Clear` method of the `Dictionary
We can clear all key-value pairs from a dictionary in C# using the `Clear` method. This example demonstrates how to remove all elements from the dictionary and print the dictionary contents before and after the clearing operation.
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"}
};
// Print the dictionary contents before clearing
Console.WriteLine("Dictionary contents before clearing:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
// Clear all key-value pairs from the dictionary
myDictionary.Clear();
// Print the dictionary contents after clearing
Console.WriteLine("Dictionary contents after clearing:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
}
}
Dictionary contents before clearing: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three Dictionary contents after clearing:
We can clear all key-value pairs from a dictionary in C# and confirm that it is empty by checking the `Count` property. This example demonstrates how to clear the dictionary and verify that it is empty.
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"}
};
// Print the dictionary contents before clearing
Console.WriteLine("Dictionary contents before clearing:");
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
}
// Clear all key-value pairs from the dictionary
myDictionary.Clear();
// Confirm the dictionary is empty
if (myDictionary.Count == 0)
{
Console.WriteLine("The dictionary is now empty.");
}
else
{
Console.WriteLine("The dictionary is not empty.");
}
}
}
Dictionary contents before clearing: Key: 1, Value: One Key: 2, Value: Two Key: 3, Value: Three The dictionary is now empty.
In this tutorial, we learned How to Clear all Key-Value Pairs from a Dictionary in C# language with well detailed examples.