Dictionary in c#

Dictionary


A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory, because for each value there is also a key.

Program that uses Dictionary Add method [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
Dictionary<string, int> dictionary =
    new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
    }
}

Results
    Dictionary contains four keys, each associated with one value.

Foreach

Foreach loop construct
Here we use foreach syntax and KeyValuePair generics in the foreach loop. With collections like Dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and Value member.
Foreach
Program that uses foreach on Dictionary [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Example Dictionary again
	Dictionary<string, int> d = new Dictionary<string, int>()
	{
	    {"cat", 2},
	    {"dog", 1},
	    {"llama", 0},
	    {"iguana", -1}
	};
	// Loop over pairs with foreach
	foreach (KeyValuePair<string, int> pair in d)
	{
	    Console.WriteLine("{0}, {1}",
		pair.Key,
		pair.Value);
	}
	// Use var keyword to enumerate dictionary
	foreach (var pair in d)
	{
	    Console.WriteLine("{0}, {1}",
		pair.Key,
		pair.Value);
	}
    }
}

Output

cat, 2
dog, 1
llama, 0
iguana, -1

cat, 2
dog, 1
llama, 0
iguana, -1



C# ContainsKey

Dictionary
ContainsKeyis a Dictionary method. It computes the hashcode for its argument. It then checks the internal structures in the Dictionary to see if that key exists. It is extremely fast—it does no linear searching.

C# Dictionary Clear

Question and answer
Clearerases all Dictionary elements. How can we efficiently use it? In most cases, testing your Dictionary before taking an action on it is the best strategy. We explore this theory by seeing whether you should test for an empty Dictionary before clearing one.

class Program
{
    const int _max = 100000000;
    static void Main()
    {
var dict = new Dictionary<string, string>();
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
    dict.Clear();
}
s1.Stop();
var s2 = Stopwatch.StartNew();
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"));
Console.Read();
    }
}

Output

3.17 ns
0.64 ns

Comments