Summary: in this tutorial, you’ll learn how to use the C# Dictionary<Tkey, TValue> class to manage dictionaries effectively.
Introduction to the C# Dictionary<TKey,TValue>
The Dictionary<TKey,TValue> class represents a collection of keys and values. It belongs to the System.Collections.Generic namespace. The TKey and TValue are the types of keys and values in the dictionary.
Every key in a dictionary must be unique. Also, a key cannot be null if its type is a reference type. If a key is an object, it must not change in any way that affects its uniqueness (or hash value).
Because C# implements Dictionary<TKey, TValue) as a hashtable, retrieving a value by key is very fast.
Create a dictionary
The following creates a dictionary in which both keys and values are strings:
Dictionary<string,string> states = new Dictionary<string,string>();Code language: C# (cs)Alternatively, you can use the var keyword:
var states = new Dictionary<string, string>();Code language: C# (cs)Populating dictionary
To add the specified key and value to a dictionary, you use the Add() method. For example, the following adds three key/value pairs to the states dictionary:
var states = new Dictionary<string,string>();
states.Add("CA", "California");
states.Add("TX", "Texas");
states.Add("NY", "New York");Code language: C# (cs)In this example, the keys are the state abbreviation and the values are the state names.
Also, you can use a collection initializer to add key/value pairs to a dictionary when you create it. For example:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};Code language: C# (cs)In this syntax, you place a key/value pair inside curly braces and wrap all elements in outer curly braces.
Retrieving an element from a dictionary
To access an element, you use a square bracket and the key of the element like this:
dict[key]Code language: CSS (css)For example, the following shows how to access the elements with keys “CA” and “NY”:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
Console.WriteLine(states["CA"]);
Console.WriteLine(states["NY"]);Code language: C# (cs)Output:
California
New YorkCode language: plaintext (plaintext)If you attempt to use a key that doesn’t exist, you’ll get a KeyNotFound exception:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
Console.WriteLine(states["AZ"]); // ExceptionCode language: C# (cs)Fortunately, you can check if a key exists before accessing the element by using the ContainKeys() method like this:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
if (states.ContainsKey("AZ"))
{
Console.WriteLine(states["AZ"]);
}
else
{
Console.WriteLine("No state with the abbreviation AZ exists");
}Code language: C# (cs)Output:
No state with the abbreviation AZ existsCode language: plaintext (plaintext)Also, you can use the TryGetValue() method if you’re unsure whether the key exists:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
string state;
if(states.TryGetValue("CA", out state))
{
Console.WriteLine(state);
}Code language: C# (cs)Output:
CaliforniaIterating through a dictionary
To iterate all elements of a dictionary, you use the foreach statement. The following example uses the foreach statement to iterate over all elements in the states dictionary:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
foreach (var state in states)
{
Console.WriteLine($"{state.Key}: {state.Value}");
}Code language: C# (cs)In each iteration, the foreach statement assigns the current dictionary’s element to the state variable.
The type of each element is the struct KeyValuePair<TKey,TValue> which contains two properties: Key and Value.
To access all the keys of a dictionary, you use the Keys property. For example:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
foreach (var stateAbbr in states.Keys)
{
Console.WriteLine(stateAbbr);
}Code language: C# (cs)Output:
CA
TX
NYCode language: plaintext (plaintext)To access only the values of a dictionary, you use the Values property. For example:
var states = new Dictionary<string, string>()
{
{"CA","California" },
{"TX","Texas" },
{"NY", "New York" }
};
foreach (var stateName in states.Values)
{
Console.WriteLine(stateName);
}Code language: PHP (php)Output:
California
Texas
New YorkCode language: PHP (php)Using a dictionary to simplify the if…else statement
The following GetDay() method returns the day name based on a day number from 1 to 7 using an if...else statement:
string GetDay(int day)
{
if (day == 1)
{
return "Sunday";
}
else if (day == 2)
{
return "Monday";
}
else if (day == 3)
{
return "Tuesday";
}
else if (day == 4)
{
return "Wednesday";
}
else if (day == 5)
{
return "Thursday";
}
else if (day == 6)
{
return "Friday";
}
else if (day == 7)
{
return "Saturday";
}
else
{
return "Invalid";
}
}Code language: C# (cs)To simplify the code, you can use a dictionary for looking up the day name based on a day number like this:
string GetDay(int day)
{
var days = new Dictionary<int, string>()
{
{1, "Sunday" },
{2, "Monday" },
{3, "Tuesday" },
{4, "Wednesday" },
{5, "Thursday" },
{6, "Friday" },
{7, "Saturday" },
};
if (days.ContainsKey(day))
{
return days[day];
}
return "Invalid";
}Code language: C# (cs)Summary
- Use the
Dictionary<TKey,TValue>to manage dictionaries effectively. - Use the
ContainsKeyorTryGetValuemethod if you’re unsure whether the key exists or not.