Clear, Dictionary. Clear() removes all existing Dictionary keys (and their values). In most cases, testing a Dictionary before using it is the best strategy.
An experiment. We see whether you should test for an empty Dictionary before clearing one. This helps us learn how best to handle Dictionaries.
First example. This program shows how the Clear method works. After we call Clear, there are always zero elements in a Dictionary. It erases the internals.
using System.Collections.Generic;
using static System.Console;
// Create a small dictionary.// ... Add 2 keys.
var lookup = new Dictionary<string, int>();
lookup["cat"] = 10;
lookup["dog"] = 20;
// Write the count.
WriteLine(lookup.Count);
// Clear the dictionary and write its new count.
lookup.Clear();
WriteLine(lookup.Count);2
0
Benchmark, clear. A Dictionary is complex. Some actions may be slower than you think. The Count and Clear members both seem simple. But the Count property is much faster than Clear.
Version 2 This code uses Clear but only when there are 1 or more elements in the Dictionary. So it can avoid calling Clear.
Result Tested in .NET 5, version 2 is faster. It is best to call Count before calling Clear.
using System;
using System.Collections.Generic;
using System.Diagnostics;
const int _max = 100000000;
var dict = new Dictionary<string, string>();
var s1 = Stopwatch.StartNew();
// Version 1: use Clear.
for (int i = 0; i < _max; i++)
{
dict.Clear();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use Clear if needed.
for (int i = 0; i < _max; i++)
{
if (dict.Count > 0)
{
dict.Clear();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));1.88 ns Always call Clear
1.04 ns Call Clear if Count > 0
Summary. Often we need to erase all the elements in a C# Dictionary. This allows us to reuse an existing Dictionary. The Clear() method helps here.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Oct 24, 2023 (edit).