Dictionary Using C# 101

Introduction and Background

 
In this article, we are going to dive into the world of dictionaries using C#. Dictionaries are exciting to learn, especially if you are already familiar with arrays and lists. However; before proceeding I highly recommend knowing and understanding the basics of arrays and/or lists, but it doesn’t hurt if you decided to continue.
 
In years of my experience creating software, I’ve seen developers who really love arrays and lists. However; many of them aren’t comfortable using dictionaries. That’s why I decided to write one about dictionaries using C# and, in this post, will try to tackle most of the basics so it can help you get started.
 

What is a Dictionary?

 
In the context of programming, a dictionary is basically a collection of keys and values. So key-value pair collection has a set of keys and each key has an associated value to it. Within the .NET framework/.NET Core, a dictionary class provides an indexed way of looking up values by key e.g. fruits["mango"]. Unlike list and arrays are accessed using a positional index number e.g. fruits[0]. 
 
Things to remember about Dictionary,
  • Dictionaries can’t have same keys
  • Dictionaries can’t have null keys

Dictionary using C# 101 

 
Ways to instantiate a Dictionary
  1. IDictionary<stringstring> countries = new Dictionary<stringstring>();  
  2.               
  3. Dictionary<stringstring> asianCountries = new Dictionary<stringstring>();  
As you can see the above statements are valid to create a new instance of a Dictionary.
 
You could either choose any of the two, just choose one for your personal preference or your team's preference. 
 
Now to test if the two statements are valid, see a unit test code below.
  1. [Fact]  
  2. public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance()  
  3. {  
  4.     IDictionary<stringstring> countries = new Dictionary<stringstring>();  
  5.       
  6.     Assert.NotNull(countries);  
  7.   
  8.     Dictionary<stringstring> asianCountries = new Dictionary<stringstring>();  
  9.   
  10.     Assert.NotNull(asianCountries);  
  11. }  
I know you're excited to see how to create a dictionary and see different ways to initialize it.
 
Let us see some code samples below. 
  1. Dictionary<stringstring> asianCountries = new Dictionary<stringstring>();  
  2.   
  3. asianCountries.Add("PH""Philippines");  
  4.   
  5. Dictionary<stringstring> asianCountries2 = new Dictionary<stringstring>  
  6. {  
  7.     { "PH""Philippines" }  
  8. };  
  9.   
  10. Dictionary<stringstring> asianCountries3 = new Dictionary<stringstring>  
  11. {  
  12.     ["PH"] = "Philippines"  
  13. };  
Let us see this in a unit test. 
  1. [Fact]  
  2. public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance_And_Initialize()  
  3. {  
  4.     Dictionary<stringstring> asianCountries = new Dictionary<stringstring>();  
  5.   
  6.     asianCountries.Add("PH""Philippines");  
  7.   
  8.     Dictionary<stringstring> asianCountries2 = new Dictionary<stringstring>  
  9.     {  
  10.         { "PH""Philippines" }  
  11.     };  
  12.   
  13.     Dictionary<stringstring> asianCountries3 = new Dictionary<stringstring>  
  14.     {  
  15.         ["PH"] = "Philippines"  
  16.     };  
  17.   
  18.     Assert.NotNull(asianCountries);  
  19.     Assert.NotNull(asianCountries2);  
  20.     Assert.NotNull(asianCountries3);  
  21. }  
In this section, will try to see how to add items within a dictionary collection.
 
Let us discuss the usage of the Add() and TryAdd() method. These two behave differently, just remember that when you try to use the Add() method it will definitely throw an exception when a key already exists. However; the TryAdd() method will try its best to add the new item and returns if it was successfully added or not. Lastly, both methods will throw an exception when the passed key is null
 
Let us see the behaviors of these two methods via adding an existing key and passing a null key value by looking at the sample codes below. 
  1. [Fact]  
  2. public void Test_Dictionary_Cant_Have_A_Null_Key()  
  3. {  
  4.     Dictionary<stringstring> nullDictionary = new Dictionary<stringstring> { };  
  5.   
  6.     nullDictionary.Add("USA"null); //passed when adding a null value  
  7.   
  8.     //throws an exception when adding a null as key  
  9.     Assert.Throws<ArgumentNullException>(() => nullDictionary.Add(nullnull));  
  10.     Assert.Throws<ArgumentNullException>(() => nullDictionary.TryAdd(nullnull));  
  11. }  
  1. [Fact]  
  2. public void Test_Dictionary_Cant_Have_Same_Key()  
  3. {  
  4.     Dictionary<stringstring> sampleDictionary = new Dictionary<stringstring>();  
  5.   
  6.     sampleDictionary.Add("MJ""Michael Jordan");  
  7.   
  8.     //throws an exception when adding an existing key  
  9.     Assert.Throws<ArgumentException>(() => sampleDictionary.Add("MJ""Magic Johnson"));  
  10.   
  11.     //TryMethod tries to add a new key but fails because MJ already exists  
  12.     Assert.False(sampleDictionary.TryAdd("MJ""Magic Johnson"));  
  13. }  
Let us try to see more examples.
  1. [Fact]  
  2. public void Test_Dictionary_To_Add()  
  3. {  
  4.     var basketBallPlayers = new Dictionary<stringstring>();  
  5.   
  6.     basketBallPlayers.Add("MJ""Michael Jordan");  
  7.   
  8.     bool successInAdding_MJ_Key = basketBallPlayers.TryAdd("MJ""Magic Johnson");  
  9.   
  10.     if (!successInAdding_MJ_Key)  
  11.     {  
  12.         basketBallPlayers.TryAdd("KD""Kevin Durant");  
  13.     }  
  14.   
  15.     Assert.Collection(basketBallPlayers,  
  16.                         item => Assert.Contains("MJ", item.Key),  
  17.                         item => Assert.Contains("KD", item.Key));  
  18. }  
In this section, let us try to see some examples on how to get those values via the usage of key and TryGetValue() method.
 
It is really easy to get the value via the key. Just remember that if your keys don't exist it will throw an exception. 
 
Now, how about when you aren't sure if the key exists. I suggest you use the TryGetValue() method.
 
Let us see them in action. 
  1. [Fact]  
  2. public void Test_Dictionary_GetValues()  
  3. {  
  4.     var basketBallPlayers = new Dictionary<stringstring>  
  5.     {  
  6.         ["MJ"] = "Michael Jordan",  
  7.         ["KD"] = "Kevin Durant"  
  8.     };  
  9.   
  10.     //gets the value of the keys: MJ and KD  
  11.     Assert.True(!string.IsNullOrEmpty(basketBallPlayers["MJ"]));  
  12.     Assert.True(!string.IsNullOrEmpty(basketBallPlayers["KD"]));  
  13.   
  14.     //try to get a key that doesn't exists  
  15.     Assert.Throws<KeyNotFoundException>(() => basketBallPlayers["LJ"]);  
  16. }  
  1. [Fact]  
  2. public void Test_Dictionary_GetValues_Via_TryGetValue_Method()  
  3. {  
  4.       
  5.     var basketBallPlayers = new Dictionary<stringstring>  
  6.     {  
  7.         ["MJ"] = "Michael Jordan",  
  8.         ["KD"] = "Kevin Durant"  
  9.     };  
  10.   
  11.     string result = string.Empty;  
  12.   
  13.     //tries to get the value of LJ.  
  14.     //if doesn't exists the string result will be equivalent to null.  
  15.     basketBallPlayers.TryGetValue("LJ"out result);   
  16.   
  17.     //once equivalent to null. Let's add LJ  
  18.     if (string.IsNullOrEmpty(result))  
  19.     {  
  20.         basketBallPlayers.Add("LJ""Larry Johnson");  
  21.     }  
  22.   
  23.     //let's try againg if LJ exits and get the value  
  24.     basketBallPlayers.TryGetValue("LJ"out result);  
  25.   
  26.     //now it does exist  
  27.     Assert.True(!string.IsNullOrEmpty(result));  
  28. }  
In this section, how about removing the item within the collection. Removing an item within the collection, we can use the Remove() method. Just remember that don't pass a null key within the method because it will throw an exception. See an example below. 
  1. [Fact]  
  2. public void Test_Dictionary_Remove_Item_WithIn_The_Collection()  
  3. {  
  4.     //initialize new basketaball players  
  5.     var basketBallPlayers = new Dictionary<stringstring>  
  6.     {  
  7.         ["MJ"] = "Michael Jordan",  
  8.         ["KD"] = "Kevin Durant",  
  9.         ["KJ"] = "Kill Joy"  
  10.     };  
  11.   
  12.     Assert.Throws<ArgumentNullException>(() => basketBallPlayers.Remove(null));  
  13.   
  14.     //let us remove the key MJ  
  15.     var removedAtFirstAttempt = basketBallPlayers.Remove("MJ");  
  16.   
  17.     Assert.True(removedAtFirstAttempt);  
  18.   
  19.     //let us try to remove MJ a non existing key  
  20.     var removedAtSecondAttempt = basketBallPlayers.Remove("MJ");  
  21.   
  22.     Assert.False(removedAtSecondAttempt);  
  23. }  
In this last section, we are going to discuss how to update the dictionaries' values. Basically you just need to set the dictionary key with a new value. 
e.g. 
  1. basketBallPlayers["KJ"] = "Kevin Johnson";  
Easy right? However; what if you want to check the key first then update the current value to a new one. We can use the ContainsKey() and/or ContainsValue() method.
  1. [Fact]  
  2. public void Test_Dictionary_GetValues_And_Update()  
  3. {  
  4.     //initialize new basketaball players  
  5.     var basketBallPlayers = new Dictionary<stringstring>  
  6.     {  
  7.         ["MJ"] = "Michael Jordan",  
  8.         ["KD"] = "Kevin Durant",  
  9.         ["KJ"] = "Kill Joy"  
  10.     };  
  11.   
  12.     //let us check if the dictionary collection contains a KJ key  
  13.     if (basketBallPlayers.ContainsKey("KJ"))   
  14.     {  
  15.         //update the value of KJ key  
  16.         basketBallPlayers["KJ"] = "Kevin Johnson";  
  17.   
  18.         Assert.True(basketBallPlayers["KJ"] == "Kevin Johnson");  
  19.     }  
  20.   
  21.     //let us check if the dictionary collection contains a Michael Jordan as value  
  22.     if (basketBallPlayers.ContainsValue("Michael Jordan"))   
  23.     {  
  24.         var result = basketBallPlayers.FirstOrDefault(value => value.Value == "Michael Jordan");  
  25.           
  26.         //update the value from Michael Jordan to Magic Johnson  
  27.         basketBallPlayers[result.Key] = "Magic Johnson";  
  28.   
  29.         Assert.True( basketBallPlayers[result.Key] != "Michael Jordan");  
  30.         Assert.True(basketBallPlayers[result.Key] == "Magic Johnson");  
  31.     }  
  32. }  

Summary and Remarks

 
Great! You have read this far. Now that you have seen how dictionaries work,  I’m hoping this post can help you get started implementing dictionaries in your current work/project. To summarize this article, we have explored the following:
  • Create a new instance of Dictionary
  • Different ways to initialize a Dictionary
  • Adding new item within the Dictionary collection
  • Removing an item within the Dictionary collection
  • Updating an item within the Dictionary collection
By the way, you can download the sample code here at GitHub or you can download the sample code attached to this article.
 
I hope you have enjoyed this article. Until next time, happy programming.