C#.Net Dictionary Table class

C#.Net Dictionary Table class
SharePoint deveopment training course

This C#.Net tutorial, we will discuss C#.Net Dictionary Table class. How To Declare A Dictionary Table Class in C#.Net? How to Add item to a Dictionary Class in C#.Net? How to retrieve the Dictionary element using the “foreach” loop in C#.Net? Retrieve Individual value using the key in C#.net.

We will discuss C#.Net dictionary table class in C#.Net.

C#.Net Dictionary Table class

In this Dictionary Table class, the hashtable key and value concept is used. Like hashtable, the dictionary contains two value one is key and another one is value and key and value combined make an element. Make sure that the key value should unique and distinct should not be null.

The Dictionary Table class comes under collection generic type so before using the Dictionary we need to add the namespace of System.Collections.Generic.

How To Declare A Dictionary Table Class in C#.Net?

To use the Dictionary table class we need to create an instance for it, instead of the dictionary we can also use IDictionary interface. Before declaration adds the namespace for generic class.

Note: It always recommended to use the interface (IDictionary) in place of class(Dictionary).

Using following syntax we can create an instance and assign to a variable.

Dictionary<key type, value type> variable name=new Dictionary<data type for key, data type for value>();

Example: Dictionary <int,string> dictnry=new Dictionary<int,string>(); we can also write like below IDictionary<int,string> dictnry=new IDictionary<int,string>();

In the above example, the key data type is an integer and the value data type is a string. We assign the object of Dictionary class to “dictnry” variable.

How to Add item to a Dictionary Class in C#.Net?

We can add the value to the Dictionary Class using the Add method. The Add method has two parameters we need to pass one is key and another one is value. In the Dictionary class declaration, I have mentioned that key data type is integer and value data type is a string.

If we add wrong data type it will through a message of syntax error. Add method syntax is a variable name which we created during declaration.Add(key,value).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dictnry = new Dictionary<int, string>();
            dictnry.Add(30, "Fail");
            dictnry.Add(40, "JustPass");
            dictnry.Add(50, "Pass");
            dictnry.Add(60, "Good,Need Improvement");
            dictnry.Add(70, "Best");
            dictnry.Add(80, "Excellent");
            dictnry.Add(90, "Outstanding");
          }
    }
}

Without using the Add method also we can add the value to dictionary class. We can add the key and value during the Dictionary class declaration. Below one is one example of add element to dictionary class.

Dictionary<int, string> dictnry = new Dictionary<int, string>()
                                            {
                                                {30,"Fail"},
                                                {40, "Pass"},
                                                {60, "Good,Need Improvement"},
                                                {90,"Outstanding" }

                                            };

How to retrieve the Dictionary element using the “foreach” loop in C#.Net?

We can display all the dictionary class element using the foreach loop. In the foreach loop we need to pass both the key and value data type like “KeyValuePair(<int,string>”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
           Dictionary<int, string> dictnry = new Dictionary<int, string>()
                                            {
                                                {30,"Fail"},
                                                {40, "Pass"},
                                                {60, "Good,Need Improvement"},
                                                {90,"Outstanding" }

                                            };
            foreach (KeyValuePair<int, string> keyandvalue in dictnry)
            {
                Console.WriteLine("Key: {0}, Value: {1}", keyandvalue.Key, keyandvalue.Value);
            }
        }
    }
}
c# dictionary foreach
c# dictionary foreach

Retrive Indivisual value using the key:

In the above example, we saw how to retrieve all the Dictionary class element using the foreach loop now we will see how to retrieve individual element from the dictionary class. For displaying the indivisual element of dictionary class I have added Console.WriteLine(variablename[pass the key]). Then it will display the value of the respective key.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
           Dictionary<int, string> dictnry = new Dictionary<int, string>()
                                            {
                                                {30,"Fail"},
                                                {40, "Pass"},
                                                {60, "Good,Need Improvement"},
                                                {90,"Outstanding" }

                                            };
            Console.WriteLine(dictnry[30]);
            Console.WriteLine(dictnry[90]);
            Console.WriteLine(dictnry[60]);
           
        }
    }
}
for each in dictionary c#
for each in dictionary c#

More Properties and Method of Dictionary Class

Count Property: The count property will show a total number of the element(key/value pairs) present in the dictionary class. The return type of count is an integer.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
           Dictionary<int, string> dictnry = new Dictionary<int, string>()
                                            {
                                                {30,"Fail"},
                                                {40, "Pass"},
                                                {60, "Good,Need Improvement"},
                                                {90,"Outstanding" }

                                            };
            if (dictnry.Count <= 10)
            {
                Console.WriteLine("Your Dictionary contains less then 10 elements");
            }
            else
            {
                Console.WriteLine("Your Dictionary contains more then 10 elements");
            }

        }
    }
}
c# dictionary count values
c# dictionary count values

Item Property: The Items propeties help us to get and set the element of dictionary with specified key.

set element syntax: “variable[key]=value;”

get element syntax:”dictnry[key]”, in the console.writeline I have prienter the value of “dictnry[100]”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dictnry = new Dictionary<int, string>()
                                            {
                                                {30,"OpearatingSystem"},
                                                {40, "Physics"},
                                                {60, "Bilogy"},
                                                {90,"Mathmatics"},
                                                {100,"Chemestry" }

                                            };
            foreach (KeyValuePair<int, string> item in dictnry)
            {
                Console.WriteLine("Key = {0}, Value = {1}",
                                  item.Key, item.Value);
            }
            dictnry[100] = "C Prorgraming";
            Console.WriteLine("After set the value");
            Console.WriteLine(dictnry[100]);
            foreach (KeyValuePair<int, string> item in dictnry)
            {
                Console.WriteLine("Key = {0}, Value = {1}",
                                  item.Key, item.Value);

            }
        }
    }
}
c# dictionary get value by key
c# dictionary get value by key

Key and value propety:

Key: The key propety will show the collections of keys of dictionary class.

Value: The Value propety will show the collections of value of dictionary class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictnory =
                       new Dictionary<string, string>();

            // Adding key/value pairs in myDict 
            dictnory.Add("January", "31");
            dictnory.Add("February", "28");
            dictnory.Add("March", "31");
            dictnory.Add("April", "30");
            dictnory.Add("May", "31");
            dictnory.Add("June","30");
            dictnory.Add("July", "31");
            Dictionary<string, string>.KeyCollection keys = dictnory.Keys;
            foreach (string Keyitems in keys)
            {
                Console.WriteLine("Key = {0}", Keyitems);
            }
            Dictionary<string, string>.ValueCollection values = dictnory.Values;
            foreach (string Valueitem in values)
            {
                Console.WriteLine("Value={0} ", Valueitem);
            }
        }
    }
}
c# dictionary get value and key
c# dictionary get value and key

TryGetValue method: Using this method we can get the value of the specified key. If the key does not exist then it will show false.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictinory = new Dictionary<string, string>()
                                {
                                    {"BBSR","Odisha"},
                                    {"Benglore", "Karnataka"},
                                    {"Guntur","AndhraPradesh"},
                                    {"Chennai","Tamilnadu" }
                                };

            if (dictinory.TryGetValue("Kerla", out  string valueofKey))
            {
                Console.WriteLine(valueofKey);
            }
            else
            {
                Console.WriteLine("Can not find the specified key value");
            }
        }
    }
}

Remove method(): The remove method will delete the value of specified key from the dictionary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictnory = new Dictionary<string, string>()
                                            {
                                                {"Season1","Summer"},
                                                {"Season2", "Rain"},
                                                {"Season3","Winter"}, {"Season4","Spring"},{"Season5","Autumn"}};
                                           
            
            foreach (KeyValuePair<string, string> keyandvalue in dictnory)
            {
                Console.WriteLine("Key: {0}, Value: {1}", keyandvalue.Key, keyandvalue.Value);
            }
            dictnory.Remove("Season3");
            Console.WriteLine("After remove the values are");
            foreach (KeyValuePair<string, string> keyandvalue in dictnory)
            {
                Console.WriteLine("Key: {0}, Value: {1}", keyandvalue.Key, keyandvalue.Value);
            }
        }
    }
}
c# dictionary collection class remove items
c# dictionary collection class remove items

ContainsKey() method: The ContainsKey() method will check whether the specified key value exists in the dictionary class or not.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictnory = new Dictionary<string, string>()
                                            {
                                                {"Season1","Summer"},
                                                {"Season2", "Rain"},
                                                {"Season3","Winter"}, {"Season4","Spring"},{"Season5","Autumn"}};
                if (dictnory.ContainsKey("Season6"))
                {
                    Console.WriteLine("The Season6 is present in the dictionary");
                }
               else
                {
                    Console.WriteLine("Doesnot exist");
                 }
        }
    }
}
c# dictionary containskey
c# dictionary containskey

ConatainsValue() method: The ContainsValue method is used to check specified value is exist in the dictionary class or not.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictnory = new Dictionary<string, string>()
                                            {
                                                {"Season1","Summer"},
                                                {"Season2", "Rain"},
                                                {"Season3","Winter"}, {"Season4","Spring"},{"Season5","Autumn"}};
                if (dictnory.ContainsValue("Rain"))
                {
                    Console.WriteLine("The Rain value is present in the dictionary");
                }
               else
                {
                    Console.WriteLine("Doesnot exist");
                 }
        }
    }
}
c# dictionary contains value
c# dictionary contains value

Clear Method: The Clear method is used to clear all the element(Key/Value) from the dictionary class. We can check successfully all item deleted or not using the count property.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> dictnory = new Dictionary<string, string>()
                                            {
                                                {"Season1","Summer"},
                                                {"Season2", "Rain"},
                                                {"Season3","Winter"}, {"Season4","Spring"},{"Season5","Autumn"}};
            dictnory.Clear();
            Console.WriteLine(dictnory.Count);
        }
    }
}
dictionary clear c#
dictionary clear c#

Equal method: This method will check between two dictionary class whether they are the same or different. The output will come in true and false value. We need to pass the dictionary class name in the equals method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> dicForElectronicsForHome = new Dictionary<string, int>()
                                            {
                                                {"SonyTV",35000},
                                                {"LgtV", 89000},
                                                {"TCLTv",24000}, {"PanasonicsTV",42000},{"Philips",67000}};
            Dictionary<string, int> dicHome = new Dictionary<string, int>()
                                            {
                                                {"Chair",3500},
                                                {"Bed", 8900},
                                                {"PressureCooker",2400}, {"CookWearSeats",4200},{"LunchBoxes",670}};
            Dictionary<string, int> dicForElectronicsForOffice = new Dictionary<string, int>();
            dicForElectronicsForHome = dicForElectronicsForOffice;
            Console.WriteLine(dicForElectronicsForHome.Equals(dicHome));
            Console.WriteLine(dicForElectronicsForHome.Equals(dicForElectronicsForOffice));
        }
    }
}
c# dictionary equals
c# dictionary equals

GetEnumerator(): The GetEnumerator method is used to return an enumerator that iterates through the dictionary collection class. Enumerators are used to reading a set of data from the collection class like for each loop. The position of an enumerator is before the first element so always we need to call the MoveNext() method. Make sure that in the below program we need to add System.Collection namespace otherwise when we add IDictionaryEnumerator interface it will show an error.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace DictionaryCollection {

    class Program
    {

        // Driver code 
        public static void Main()
        {

            // Creating a Dictionary named myDict 
            Dictionary<string, int> dicProduct =
               new Dictionary<string,int>();

            dicProduct.Add("SonyMobile",23000);
            dicProduct.Add("HeadPhone", 2300);
            dicProduct.Add("Telivision",60000);
            dicProduct.Add("Laptop", 100000);
            dicProduct.Add("WaterPurifier",12000);
            IDictionaryEnumerator enumerator =
                         dicProduct.GetEnumerator();
            while (enumerator.MoveNext())
                Console.WriteLine(enumerator.Key +" Price is "+ enumerator.Value);
        }
    }
}
c# dictionary getenumerator
c# dictionary getenumerator

You may like following C#.Net tutorials:

In the C#.net article, we have discussed the Dictionary collection class, how to declare and initialize the dictionary class collection? We were also discussed about some of the method and property the dictionary collection class allows like add, remove property and Count method.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →