Search

Dictionary

The Dictionary type in the base class library is an important one. It is an implementation of a hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET is well-designed.

Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 // Use the dictionary.
 Dictionary dict = new Dictionary();
 dict.Add("cat", 1);
 dict.Add("dog", 4);

 Console.WriteLine(dict["cat"]);
 Console.WriteLine(dict["dog"]);
    }
}
The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary requires a special syntax form.

Add

using System;
using System.Collections.Generic;

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

Get values

Next, you can check to see if a given string is present in a Dictionary with string keys. We look at more types of Dictionaries further on, but here is the ContainsKey method. It returns true if the key was found.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Dictionary dictionary = new Dictionary();
	dictionary.Add("apple", 1);
	dictionary.Add("windows", 5);

	// See whether Dictionary contains this string.
	if (dictionary.ContainsKey("apple"))
	{
	    int value = dictionary["apple"];
	    Console.WriteLine(value);
	}

	// See whether Dictionary contains this string.
	if (!dictionary.ContainsKey("acorn"))
	{
	    Console.WriteLine(false);
	}
    }
}

KeyValuePair

When Dictionary, or any object that implements IDictionary, is used in a foreach-loop, it returns an enumeration. In the case of Dictionary, this enumeration is in the form of KeyValuePair values.

KeyValuePair stores two values together. It is a single generic struct. The KeyValuePair type in System.Collections.Generic is simple and always available. It is used internally in Dictionary and other collections.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Shows a List of KeyValuePairs.
	var list = new List>();
	list.Add(new KeyValuePair("Cat", 1));
	list.Add(new KeyValuePair("Dog", 2));
	list.Add(new KeyValuePair("Rabbit", 4));

	foreach (var element in list)
	{
	    Console.WriteLine(element);
	}
    }
}

Often, you need to return two separate values from a method. You can do this easily with KeyValuePair. You must specify the exact type in the return value, and then return the new KeyValuePair in the method body.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	Console.WriteLine(GetNames());
    }

    static KeyValuePair GetNames()
    {
	// Gets collection of first and last name.
	string firstName = "William";
	string lastName = "Gates";
	return new KeyValuePair(firstName, lastName);
    }
}

Implementation

You should know the basic layout of the KeyValuePair struct. Here, we see the internal code. The KeyValuePair has two private fields, and two public properties that retrieve the values of those fields.
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct KeyValuePair
{
    private TKey key;
    private TValue value;
    public KeyValuePair(TKey key, TValue value);
    public TKey Key { get; }
    public TValue Value { get; }
    public override string ToString();
}