In .NET, a Dictionary class is a collection of a key and value pair of data. C# represents a generic Dictionary <TKey, TValue> class that can be used to create a collection of objects. The key should be identical in a key-value pair and it can have at most one value in the dictionary. TKey represents the data type used for the dictionary’s keys, and TValue represents the data type used to store the information or data associated with a key. This class is defined in the System.Collections.Generic namespace. You should import the System.Collections.Generic namespace in code to use the dictionary.
How Do You Use Dictionaries in C#?
To explain a dictionary and how it is used with different elements, let’s create a sample key type and its value type (string, int). In the following example, I have used Add() to set 4 keys to 4 values in a dictionary. Then, ContainsKey returns true if the key is found. Refer to the following C# code snippet:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectDictionary { class Program { static void Main(string[] args) { /* Student and Roll Number */ Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("Tapas", 1); dictionary.Add("Dipak", 2); dictionary.Add("Sidhu", 3); dictionary.Add("Manoj", 4); // See whether Dictionary contains this string. if (dictionary.ContainsKey("Sidhu")) { int value = dictionary["Sidhu"]; Console.WriteLine(value); } // See whether it contains this string. if (!dictionary.ContainsKey("Lalu")) { Console.WriteLine(false); } Console.Read(); } } }
In the next example, I have again added 4 keys to 4 values in a C# dictionary. Then, the TryGetValue function is called to test for the key. It returns the value if it finds the key. The following C# code snippet explains the TryGetValue function:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectDictionary { class Program { static void Main(string[] args) { /* Student and Sports they love */ Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("Tapas", "Triathlon"); dictionary.Add("Dipak", "Cricket"); dictionary.Add("Sidhu", "Football"); dictionary.Add("Manoj", "Karate"); string test; // Returns true. if (dictionary.TryGetValue("Dipak", out test)) { Console.WriteLine(test); // This is the value at cat. } // Returns false. if (dictionary.TryGetValue("XYZ", out test)) { Console.WriteLine(false); // Not reached. } Console.Read(); } } }
Read: Working with Collections in C#
How do you use KeyValuePairs in Loops?
To explain how the dictionary KeyValuePairs could work in a loop, I have coded the following snippet. To work with collections, like a dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and a Value member:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectDictionary { class Program { static void Main(string[] args) { /* Student and Sports they love */ Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("Tapas", "Triathlon"); dictionary.Add("Dipak", "Cricket"); dictionary.Add("Sidhu", "Football"); dictionary.Add("Manoj", "Karate"); // Loop over pairs with foreach. foreach (KeyValuePair<string, string> pair in dictionary) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } // Use var keyword to enumerate dictionary. Console.WriteLine(); foreach (var pair in dictionary) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } Console.Read(); } } }
LINQ extension methods can be used with a dictionary. I have used this as an extension method on IEnumerable. It places keys and values into a new dictionary:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectDictionary { class Program { static void Main(string[] args) { Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary.Add("Tapas", 1); dictionary.Add("Dipak", 2); dictionary.Add("Sidhu", 3); dictionary.Add("Manoj", 4); // Store keys in a List. List<string> list = new List<string>(dictionary.Keys); // Loop through list. foreach (string k in list) { Console.WriteLine("{0}, {1}", k, dictionary[k]); } Console.Read(); } } }
Read: Debugging Tools for C#
C# Dictionaries and Lambda Expressions
Finally, in the last example, I have shown the use of lambda expressions. With these small functions, we specify a method directly as an argument. The following code snippet uses ToDictionary, from System.Linq, on a string array. It creates a lookup table for the strings.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectDictionary { class Program { static void Main(string[] args) { string[] arr = new string[] { "Tapas", "Dipak", "Sidhu", "Manoj" }; var dict = arr.ToDictionary(item => item, item => true); foreach (var pair in dict) { Console.WriteLine("{0}, {1}", pair.Key, pair.Value); } Console.Read(); } } }
Read: Building Lambda Expressions from Tree Expressions in C#
Conclusion to C# Dictionary Tutorial
I hope the preceding examples explain the design intentions of the C# Dictionary. Write your own samples, extend them, and keep thinking about ways to use this very fast data structure.
That’s all for today. Happy reading!