Getting Started with the Dictionary Object

The Dictionary object in C# is a fundamental aspect of the programming language and .NET CLR. Its found in similar guises in C++, Java and many more, so will likely be familiar if you have coded in other languages. The big advantage that the .NET Dictionary object has over its competitors is that it’s a generic object which means we can assign any type we want as the Key and Value. 
In this tutorial we will be looking the Dictionary object basics, how we can convert a SQL result into a dictionary object, taking a look at using LINQ to access and manipulate the data in our Dictionary objects and reviewing the most useful built in methods available for the Dictionary object. 
 
Dictionaries are Generic. 
 
The signature of the Dictionary object is Dictionary<T, T> where T is an object of any type. The first T is the Key and the second T is the Value. Although you have full freedom in how to declare a Dictionary, the most common use is to have an int for the key and a string for the value. In the examples below we will also look at a dictionary with a string as the key and a generic list as the value. 
 
Dictionary Object – the basics 
 
The code below shows how to initialise and add data to a dictionary object of type Dictionary<int, string>. It shows how you can access values by the key, check a key exists and how to clear the dictionary of data. 
[TestMethod]
public void UsingTheDictionaryObject_0()
{
	// object instantiation and adding data
	Dictionary<int, string> TagsDict = new Dictionary<int, string>();
	TagsDict.Add(1, "C#");
	TagsDict.Add(2, ".NET");

	string DictValue = TagsDict[1];
	Assert.IsTrue(DictValue == "C#");

	// ContainsKey method
	Assert.IsTrue(TagsDict.ContainsKey(2) == true);
	Assert.IsTrue(TagsDict.ContainsKey(3) == false);
	Assert.IsTrue(TagsDict.ContainsKey(0) == false);

	// Clear method
	Assert.IsTrue(TagsDict.Count == 2);

	TagsDict.Clear();

	Assert.IsTrue(TagsDict.Count == 0);
}
 
Looping through the Dictionary Object 
 
Looping through the Dictionary object is simple. Its inherits IEnumerable so you can use a foreach loop. You can also loop through the keys and values. See the example below. 
 
[TestMethod]
public void UsingTheDictionaryObject_1()
{
	Dictionary<int, string> TagsDict = new Dictionary<int, string>();

	// loop through the Dictionary
	foreach (KeyValuePair<int, string> kvp in TagsDict)
	{
		int key = kvp.Key;
		string value = kvp.Value;

		// logic here...
	}

	// loop through the keys
	foreach (int TagID in TagsDict.Keys)
	{
		// logic here...
	}

	// loop through the values
	foreach (string TagName in TagsDict.Values)
	{
		// logic here...
	}
}
 
Converting a SQL result to a Dictionary object. 
 
For this example, I will be using the Tags used in IntermittentBug. They consist of a Primary key int ID column and a string Tag name column. We can use the ToDictionary() method to convert the result into a Dictionary of type Dictionary<int, string> 
 
Lets have a look at the data. 
 
SELECT TOP (1000) [ID]
      ,[Tag]
      ,[TagURL]
      ,[Description]
  FROM [tbl_Tags]
 
This shows how the data looks in the database. We will be using LINQ  and Entity Framework to select this data. 
 
 
If your not familiar with Entity Framework or Linq the code below can look a bit cryptic so ill explain in detail what's going on.  The code uses Entity Framework to select the data from the database. The using() statement setups what's called the Database Context which we can then call SELECT, WHERE or any typical database CRUD (Create Read Update Delete) operations. For a more detailed explanation on Entity Framework, please see the Getting Started with Entity Framework tutorial. 
For the first example we care calling LINQ Select and creating an anonymous object called tag with properties ID and Tag. When we call the ToDictionary() method we can assign the Key and Value using the ID and Tag property defined in the LINQ Select. This looks a little complicated so I would recommend you follow along by writing your own code. 
Lets have a look at the C# code. All the C# examples are in a unit test class which is why we have Assert and the [TestMethod] attribute. 
 
[TestMethod]
public void UsingTheDictionaryObject_2()
{
	Dictionary<int, string> TagsDict = new Dictionary<int, string>();

	using (var DB = new IntermittentBug_EFOverride())
	{
		TagsDict = DB.tbl_Tags
			.Select(tag => new { tag.ID, tag.Tag })
			.ToDictionary(Key => Key.ID, Value => Value.Tag);
	}

	Assert.IsTrue(TagsDict.Count() > 0);
}
 
 
New Dictionary types <string, List<T>> 
 
For the final example, we will look at a more complex dictionary that contains a list of objects for the value. Using the tags dictionary we will dictate which tags are open source, which is Microsoft and add to a new dictionary that has the signature Dictionary<string, List<T>> where T is the Entity Framework database table object tbl_Tags. Lets go through the code in detail. 
To begin we are creating 2 Dictionary objects, one for the tags and one for the list of tbl_Tags which will be got from the database. Next I'm adding 2 keys "Microsoft" and Open Source. I adding new instances of type List<tbl_Tags> as the values. Then we are populating the Dictionary from the database using the ToDictionary method as explained in the first example. Now im looping through the tags dictionary and checking to see on iteration what the key is. If its 1 or 2 then it’s a Microsoft techniology so imcalling the private method GetTagFromDB which returns a tbl_Tag object. This is then added to the Microsoft List object. Key 13 is PHP so the same process for this is taking place except that im adding it to the OpenSource List. To finish im adding the lists to the TechDict Dictionary object using the keys respectively.  
 
[TestMethod]
public void UsingTheDictionaryObject_3()
{
	Dictionary<int, string> UnitTestDict = new Dictionary<int, string>();
	Dictionary<string, List<tbl_Tags>> TechDict = new Dictionary<string, List<tbl_Tags>>();

	TechDict.Add("Microsoft", new List<tbl_Tags>());
	TechDict.Add("Open Source", new List<tbl_Tags>());

	using (var DB = new IntermittentBug_EFOverride())
	{
		UnitTestDict = DB.tbl_Tags
			.Select(tag => new { tag.ID, tag.Tag })
			.ToDictionary(Key => Key.ID, Value => Value.Tag);
	}

	List<tbl_Tags> Microsoft = new List<tbl_Tags>();
	List<tbl_Tags> OpenSource = new List<tbl_Tags>();

	foreach (KeyValuePair<int, string> kvp in UnitTestDict)
	{
		if(kvp.Key == 1 || kvp.Key == 2)
		{
			Microsoft.Add(GetTagFromDB(kvp.Key));
		}
		if(kvp.Key == 13)
		{
			OpenSource.Add(GetTagFromDB(kvp.Key));
		}
	}

	TechDict["Microsoft"] = Microsoft;
	TechDict["Open Source"] = OpenSource;
}

private tbl_Tags GetTagFromDB(int ID)
{
	tbl_Tags tag = new tbl_Tags();

	using (var DB = new IntermittentBug_EFOverride())
	{
		tag = DB.tbl_Tags.Where(x => x.ID == ID).SingleOrDefault();
	}

	return tag;
}
 
Using LINQ with Dictionary Objects 
 
Below are some examples of how to use LINQ with the Dictionary object. Some are very useful others are simply examples of what can be done.
 
var GetVBValue = TagsDict.Where(x => x.Value == "VB.NET").SingleOrDefault();

var EvenKeys = TagsDict.Where(kvp => kvp.Key % 2 == 0).ToDictionary(k => k.Key, v => v.Value);

var OddKeys = TagsDict.Where(kvp => kvp.Key % 2 != 0).ToDictionary(k => k.Key, v => v.Value);

var KeysSum = TagsDict.Sum(x => x.Key);

var kvpIndex4 = TagsDict.ElementAtOrDefault(4);

var maxKey = TagsDict.Select(x => x.Key).Max(x => x);

var minKey = TagsDict.Select(x => x.Key).Min(x => x);

var AvgKey = TagsDict.Select(x => x.Key).Average(x => x);

var FirstKVP = TagsDict.FirstOrDefault();

var LastKVP = TagsDict.LastOrDefault();

JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline


Tutorial Statistics
  • Views: 1132
  • Comments: 0
  • Author: JGilmartin (2890)
  • Date: 2/2/2017 19:40
Tags
C# .NET

© 2016 - 2018 - IntermittentBug