dcsimg

Working with Dictionaries in C#

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


Introduction

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.

Working with Dictionaries in C#

To explain a dictionary and how it's 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 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 Dictionary. Then, the TryGetValue function is called to test for the key. It returns the value if it finds the key. The following 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();
      }
   }
}

To explain how the dictionary KeyValuePairs could work in a loop, I have coded the following snippet. To work with collections like Dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and 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 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();
      }
   }
}

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();
      }
   }
}

Conclusion

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!



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date