Dictionary in C # – Part 2 of 2

For Part 1, click here.
In this second part of the series, we will see about Dictionary Class and few properties of it.

We will discuss the following methods of Dictionary Class.

  1. TryGetValue()
  2. Count()
  3. Remove()
  4. Clear()
  5. Using LINQ extension methods with Dictionary
  6. Different ways to convert an array into a Dictionary.

We will be using the same example as discussed in earlier post, please refer Part 1 for the code example. Here we have student class with 3 auto implemented properties, and in the main class method we created student objects and added to the dictionary.

Student s1 = new Student() { ID = 100, Name = "Komal", Location = "Hyderabad" };
Student s2 = new Student() { ID = 101, Name = "Jashank", Location = "Bangalore" };
Student s3 = new Student() { ID = 102, Name = "Siva", Location = "Delhi" };

//Creating a dictionary and adding students object to that.
Dictionary<int, student=""> studentDictionary = new Dictionary<int, student="">();
studentDictionary.Add(s1.ID, s1);
studentDictionary.Add(s2.ID, s2);
studentDictionary.Add(s3.ID, s3);

When do we use the method “TryGetValue”? If we are not sure if a dictionary has a value or not, then we use this method. It returns a value associated with a key, there are several ways to get the value, and one way is to directly access the dictionary with the key, if the key does not exists in the dictionary we get the exception.

1. TryGetValue method does not throw the exception if the key does not exist in the dictionary. Let us see that with an example.

Student stud;
if (studentDictionary.TryGetValue(100, out stud))
{
Console.WriteLine("Id={0}, Name={1}, Location={2}", stud.ID, stud.Name, stud.Location);
}
else
{
Console.WriteLine("The key is not found");
}

2. Now Let us see the “Count” function. If we want to find how many number of elements exists in the dictionary we use this method.

There are 2 ways to find the number of elements in the dictionary; it exposes a count property which returns the integer. There is another count function which is a LINQ extension method on IEnumerable class. There are 2 overloaded functions of this count function; here we can pass filter criteria to further limit the elements.

Notice that without including the System.Linq namespace we are not able to see the extension methods on dictionary object.

Without including System.Linq Namespace.

Without including System.Linq Namespace.

Once we include the System.Linq namespace in our program we can see the count as extension method. Ideally we can use any valid filter function in the linq query.

After including System.Linq Namespace

After including System.Linq Namespace

3. Let us discuss the remove function; If we want to remove an item simply we say as below. If I specify a key that does not exists, then we did not get any exception simply it ignores.

studentDictionary.Remove(100);

4. If we want to remove all items from the dictionary. It is going to remove everything.

studentDictionary.Clear();

5.We have seen in the above example of using LINQ Extension methods in Dictionary.

6.Let us look how to convert the different ways to convert an array in to dictionary.

Student[] studentArray = new Student[3];
studentArray[0] = s1;
studentArray[1] = s2;
studentArray[2] = s3;
Dictionary<int, student=""> sd = studentArray.ToDictionary(SA => SA.ID, SA => SA);

Instead of Array, we can convert a list in to Dictionary, let us see that quickly with the code snippet.

List studentList = new List();
studentList.Add(s1);
studentList.Add(s2);
studentList.Add(s3);
Dictionary<int, student=""> sdList = studentArray.ToDictionary(SA => SA.ID, SA => SA);

Complete Code is given below.

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Student s1 = new Student() { ID = 100, Name = "Komal", Location = "Hyderabad" };
Student s2 = new Student() { ID = 101, Name = "Jashank", Location = "Bangalore" };
Student s3 = new Student() { ID = 102, Name = "Siva", Location = "Delhi" };

//Creating a dictionary and adding students object to that.
Dictionary<int, Student> studentDictionary = new Dictionary<int, Student>();
studentDictionary.Add(s1.ID, s1);
studentDictionary.Add(s2.ID, s2);
studentDictionary.Add(s3.ID, s3);

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("TryGetValue Demo");
Console.ForegroundColor = ConsoleColor.White;
Student stud;
if (studentDictionary.TryGetValue(100, out stud))
{
Console.WriteLine("Id={0}, Name={1}, Location={2}", stud.ID, stud.Name, stud.Location);
}
else
{
Console.WriteLine("The key is not found");
}

if (studentDictionary.TryGetValue(109, out stud))
{
Console.WriteLine("Id={0}, Name={1}, Location={2}", stud.ID, stud.Name, stud.Location);
}
else
{
Console.WriteLine("The key is not found");
}

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nCount property and Count Function Demo");
Console.ForegroundColor = ConsoleColor.White;

Console.WriteLine("Total Number of students = {0} ", studentDictionary.Count);

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nCount Function Demo which is an LINQ Extension method");
Console.ForegroundColor = ConsoleColor.White;

Console.WriteLine("Total Number of students = {0} ", studentDictionary.Count());

Console.WriteLine("Total Number of students whose name is greater than 4 characters = {0} ", studentDictionary.Count(s => s.Value.Name.Length > 4));

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nConverting an Array in to Dictionary.");
Console.ForegroundColor = ConsoleColor.White;

Student[] studentArray = new Student[3];
studentArray[0] = s1;
studentArray[1] = s2;
studentArray[2] = s3;

Dictionary<int, Student> sd = studentArray.ToDictionary(SA => SA.ID, SA => SA);

Console.WriteLine("\nLooping through the sd dictionary and displaying the values.");
foreach (KeyValuePair<int, student=""> kvp in sd)
{
Console.WriteLine("Id = {0}", kvp.Key);
Student s = kvp.Value;
Console.WriteLine("Id = {0}, Name = {1}, Location = {2}", s.ID, s.Name, s.Location);
}

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nConverting a List in to Dictionary.");
Console.ForegroundColor = ConsoleColor.White;

List<Student> studentList = new List<Student>();
studentList.Add(s1);
studentList.Add(s2);
studentList.Add(s3);

Dictionary<int, student=""> sdList = studentArray.ToDictionary(SA => SA.ID, SA => SA);

Console.WriteLine("\nLooping through the sd dictionary and displaying the values.");
foreach (KeyValuePair<int, student=""> kvp in sdList)
{
Console.WriteLine("Id = {0}", kvp.Key);
Student s = kvp.Value;
Console.WriteLine("Id = {0}, Name = {1}, Location = {2}", s.ID, s.Name, s.Location);
}

Console.Write("\nPress and key to end the execution");
Console.Read();
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
}
}
}

Hope you learned about Dictionary with these 2 blog posts, let me know your thoughts on this topic further. Leave any comments and feedback below.

Happy Learning :) Thanks!!!

Posted in C# | Tagged , , | Leave a comment

Dictionary in C # – Part 1 of 2

For Part 2, click here.

In the part 1 of this post, let us discuss about Dictionary class in C#. There are lots of lots of content available explaining about this topic on the internet when you Google it, but this is my two cents of understanding on this topic.

A dictionary is a collection of <key, value=””> pairs. Dictionary class is present in System.Collections.Generic namespace. When a Dictionary is created, we need to specify the data type for Key and Value. It provides fast lookups for values using keys, last but not the least keys in the dictionary must be unique.

Let us try to understand this concept with this example. First let us create a simple student class with three auto implemented properties which will be used in the example.

       public class Student
       {
           public int ID { get; set; }
           public string Name { get; set; }
           public string Location { get; set; }
       }
 

Let us create some student objects as show in the code below. The following code snippet creates a dictionary adds students objects and reads the data back to the console with various scenarios as explained in the comments section of the code. To work with this example simply copy the below code and paste the code in a new class file.


using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Student s1 = new Student()
{
ID = 100,
Name = "Komal",
Location = "Hyderabad"
};

Student s2 = new Student()
{
ID = 101,
Name = "Jashank",
Location = "Bangalore"
};

Student s3 = new Student()
{
ID = 102,
Name = "Siva",
Location = "Delhi"
};

//Creating a dictionary and adding students object to that.
Dictionary<int, student=""> studentDictionary = new Dictionary<int, student="">();
studentDictionary.Add(s1.ID, s1);
studentDictionary.Add(s2.ID, s2);
studentDictionary.Add(s3.ID, s3);

//Finding the students from the dictionary, and the best and fastest way to find the students
//from the dictionary is by using the Id of the Student.

//Find the student with id 102.
Student student102 = studentDictionary[102];

//Print the details of the Student by Id.
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Student Details by Id \n");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Id={0}, Name={1}, Location={2}", student102.ID, student102.Name, student102.Location);
Console.WriteLine("===================================\n");

//Now Let us see how to loop through the list of students objects from the dictionary.
//Here we have to use key value pair object to loop through the dictionary objects.
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Printing Student Details using keyvaluepair object in fopreach loop\n");
Console.ForegroundColor = ConsoleColor.White;
foreach (KeyValuePair<int, student=""> eachStudent in studentDictionary)
{
Console.WriteLine("Student Key={0}", eachStudent.Key);
Student stud = eachStudent.Value;
Console.WriteLine("Id={0}, Name={1}, Location={2}", stud.ID, stud.Name, stud.Location);
Console.WriteLine("===================================\n");
}

//Instead of using key value pair object to read the dictionary, we can also use the implicit
//typed variable called "var"
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Printing Student Details using implicit type var in foreach loop\n");
Console.ForegroundColor = ConsoleColor.White;
foreach (var eachStudent in studentDictionary)
{
Console.WriteLine("Student Key={0}", eachStudent.Key);
Student stud = eachStudent.Value;
Console.WriteLine("Id={0}, Name={1}, Location={2}", stud.ID, stud.Name, stud.Location);
Console.WriteLine("===================================\n");
}

//If we want to loop over the keys and values exclusively, then it is possible in dictionary.
//Dictionary object exposes two important properties called.
//1. Keys and 2. Values
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Printing Student Key using keys collection property in dicitionary\n");
Console.ForegroundColor = ConsoleColor.White;
foreach (int key in studentDictionary.Keys)
{
Console.WriteLine("Student Key={0}", key);
Console.WriteLine("===================================\n");
}

Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Printing Student Key using Values collection property in dicitionary\n");
Console.ForegroundColor = ConsoleColor.White;
foreach (Student values in studentDictionary.Values)
{
Console.WriteLine("Id={0}, Name={1}, Location={2}", values.ID, values.Name, values.Location);
Console.WriteLine("===================================\n");
}

Console.Write("\nPress and key to end the execution");
Console.Read();
}

public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
}
}
}

One thing to keep in mind is that the keys in the dictionary must be unique; it means we cannot add duplicate keys to the dictionary object. If we try to add the same student again as shown below we get this exception.

DuplicateKeyException

To overcome the above exception, dictionary has a method called “containskey”, if you are not sure that the dictionary has that key or not we can use this method. NoDuplicateKeyException

When we are trying to read the values from the dictionary make sure that the object exists in the dictionary otherwise we get this exception while reading the data from the dictionary.KeyNotFoundException

To overcome this exception, check whether the key exists or not in the dictionary, as we have seen before while adding the key to the dictionary using “containskey”

//Check whether the key exists or not before reading the value from the dictionary.
           if (studentDictionary.ContainsKey(105))
           {
             Student noStud = studentDictionary[105];
           }

There are several other useful functions in this dictionary class; we will discuss them in the next blog post.

Happy learning :)

Please do let me know if you find any errors in the above code. I will correct it and update them in the post. Don’t forget to leave any feedback in the comments area. Thanks!!!

Posted in C# | Tagged , , | 3 Comments

How to Add Open Containing Folder in Context Menu

In the Last post we have seen how to add shortcut key to “Open Containing Folder”. Today we will see how to add the same command in Context Menu when right clicked on the code behind window.

Go to Tools Customize menu option as show below.

Customize item selection under Tools Menu.

Customize item selection under Tools Menu.

In Customize window, Click on “Commands” Tab then select “Context Menu” option Button and from the drop down box select “Editor Context Menus | Code Window”. Then Click on Add Command. Follow the steps as shown Step 1, 2, 3 and 4 in the image.

Customize Window selection.

Customize Window selection.

After clicking on the “Add Command” below screen will appear.

Add Command Window.

Add Command Window.

From the above pop-up window select “File” from left “Categories” list and “Open Containing Folder” from “Commands” list. Click on OK as shown in steps 1, 2, and 3.

Position of Open Containing Folder.

Position of Open Containing Folder.

Now you can see “Open Containing Folder” has been added in Customize Window’s Commands Tab.

Add Command Window after adding Open Containing Folder.

Add Command Window after adding Open Containing Folder.

Here you can set the position of this feature to show in the context menu by using Move UP / Move Down to You can also click on “Keyboard …” button to give the shortcut keys from here. The process of assigning the keyboard shortcut is same as we have seen in my last post. Click Here to see that tip.

That’s it, you are done. now you can right-click on code behind file and select ”Open Containing Folder” to open the current opened files in Windows Explorer as show below.

Open Containing Folder in Context Menu.

Open Containing Folder in Context Menu.

Summary: In this blog post I described a small tip on how we can use “Open Containing Folder” feature from Context Menu and in the Last post we have seen how to Open Containing Explorer Folder in Visual Studio by assigning a shortcut key for the same feature. These are minor tips but are handy in daily activities.

Hope this will help you! Don’t forget to leave any feedback in the comments area. Happy Learning. :)

Posted in .NET, Productivity Tips in Visual Studio IDE. | Tagged , | 1 Comment