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
- IDictionary<string, string> countries = new Dictionary<string, string>();
-
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
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.
- [Fact]
- public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance()
- {
- IDictionary<string, string> countries = new Dictionary<string, string>();
-
- Assert.NotNull(countries);
-
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
-
- Assert.NotNull(asianCountries);
- }
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.
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
-
- asianCountries.Add("PH", "Philippines");
-
- Dictionary<string, string> asianCountries2 = new Dictionary<string, string>
- {
- { "PH", "Philippines" }
- };
-
- Dictionary<string, string> asianCountries3 = new Dictionary<string, string>
- {
- ["PH"] = "Philippines"
- };
Let us see this in a unit test.
- [Fact]
- public void Test_Dictionary_Different_Ways_To_Create_A_New_Instance_And_Initialize()
- {
- Dictionary<string, string> asianCountries = new Dictionary<string, string>();
-
- asianCountries.Add("PH", "Philippines");
-
- Dictionary<string, string> asianCountries2 = new Dictionary<string, string>
- {
- { "PH", "Philippines" }
- };
-
- Dictionary<string, string> asianCountries3 = new Dictionary<string, string>
- {
- ["PH"] = "Philippines"
- };
-
- Assert.NotNull(asianCountries);
- Assert.NotNull(asianCountries2);
- Assert.NotNull(asianCountries3);
- }
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.
- [Fact]
- public void Test_Dictionary_Cant_Have_A_Null_Key()
- {
- Dictionary<string, string> nullDictionary = new Dictionary<string, string> { };
-
- nullDictionary.Add("USA", null);
-
-
- Assert.Throws<ArgumentNullException>(() => nullDictionary.Add(null, null));
- Assert.Throws<ArgumentNullException>(() => nullDictionary.TryAdd(null, null));
- }
- [Fact]
- public void Test_Dictionary_Cant_Have_Same_Key()
- {
- Dictionary<string, string> sampleDictionary = new Dictionary<string, string>();
-
- sampleDictionary.Add("MJ", "Michael Jordan");
-
-
- Assert.Throws<ArgumentException>(() => sampleDictionary.Add("MJ", "Magic Johnson"));
-
-
- Assert.False(sampleDictionary.TryAdd("MJ", "Magic Johnson"));
- }
Let us try to see more examples.
- [Fact]
- public void Test_Dictionary_To_Add()
- {
- var basketBallPlayers = new Dictionary<string, string>();
-
- basketBallPlayers.Add("MJ", "Michael Jordan");
-
- bool successInAdding_MJ_Key = basketBallPlayers.TryAdd("MJ", "Magic Johnson");
-
- if (!successInAdding_MJ_Key)
- {
- basketBallPlayers.TryAdd("KD", "Kevin Durant");
- }
-
- Assert.Collection(basketBallPlayers,
- item => Assert.Contains("MJ", item.Key),
- item => Assert.Contains("KD", item.Key));
- }
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.
- [Fact]
- public void Test_Dictionary_GetValues()
- {
- var basketBallPlayers = new Dictionary<string, string>
- {
- ["MJ"] = "Michael Jordan",
- ["KD"] = "Kevin Durant"
- };
-
-
- Assert.True(!string.IsNullOrEmpty(basketBallPlayers["MJ"]));
- Assert.True(!string.IsNullOrEmpty(basketBallPlayers["KD"]));
-
-
- Assert.Throws<KeyNotFoundException>(() => basketBallPlayers["LJ"]);
- }
- [Fact]
- public void Test_Dictionary_GetValues_Via_TryGetValue_Method()
- {
-
- var basketBallPlayers = new Dictionary<string, string>
- {
- ["MJ"] = "Michael Jordan",
- ["KD"] = "Kevin Durant"
- };
-
- string result = string.Empty;
-
-
-
- basketBallPlayers.TryGetValue("LJ", out result);
-
-
- if (string.IsNullOrEmpty(result))
- {
- basketBallPlayers.Add("LJ", "Larry Johnson");
- }
-
-
- basketBallPlayers.TryGetValue("LJ", out result);
-
-
- Assert.True(!string.IsNullOrEmpty(result));
- }
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.
- [Fact]
- public void Test_Dictionary_Remove_Item_WithIn_The_Collection()
- {
-
- var basketBallPlayers = new Dictionary<string, string>
- {
- ["MJ"] = "Michael Jordan",
- ["KD"] = "Kevin Durant",
- ["KJ"] = "Kill Joy"
- };
-
- Assert.Throws<ArgumentNullException>(() => basketBallPlayers.Remove(null));
-
-
- var removedAtFirstAttempt = basketBallPlayers.Remove("MJ");
-
- Assert.True(removedAtFirstAttempt);
-
-
- var removedAtSecondAttempt = basketBallPlayers.Remove("MJ");
-
- Assert.False(removedAtSecondAttempt);
- }
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.
- 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.
- [Fact]
- public void Test_Dictionary_GetValues_And_Update()
- {
-
- var basketBallPlayers = new Dictionary<string, string>
- {
- ["MJ"] = "Michael Jordan",
- ["KD"] = "Kevin Durant",
- ["KJ"] = "Kill Joy"
- };
-
-
- if (basketBallPlayers.ContainsKey("KJ"))
- {
-
- basketBallPlayers["KJ"] = "Kevin Johnson";
-
- Assert.True(basketBallPlayers["KJ"] == "Kevin Johnson");
- }
-
-
- if (basketBallPlayers.ContainsValue("Michael Jordan"))
- {
- var result = basketBallPlayers.FirstOrDefault(value => value.Value == "Michael Jordan");
-
-
- basketBallPlayers[result.Key] = "Magic Johnson";
-
- Assert.True( basketBallPlayers[result.Key] != "Michael Jordan");
- Assert.True(basketBallPlayers[result.Key] == "Magic Johnson");
- }
- }
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.