ARTICLE

Dictionary in C#

Posted by Mahesh Chand Articles | C# Language July 10, 2010
A Dictionary class represents a dictionary in C# that is used to represent a collection of keys and values pair of data. This article demonstrates how to use a dictionary in C#.
Reader Level:

Introduction

A Dictionary class represents a dictionary in C# that is used to represent a collection of keys and values pair of data. This article demonstrates how to use a dictionary in C#.

Creating a Dictionary

The Dictionary class is a generic class and can store any data types. This class is defined in the System.Collections.Generic namespace. Before you use a Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.

using System.Collections.Generic;

The Dictionary class constructor takes two parameters (generic type), first for the type of the key and second for the type of the value. The following code snippet creates a Dictionary where keys are strings and values are short. 

Dictionary<stringInt16> AuthorList = new Dictionary<stringInt16>();

Add and Read Data


As other collection classes, the Dictionary class has Add, Remove, Clear and other collection methods. The Key and Value property are used to extract a key and a value from an item in a Dictionary.

 

The following code snippet creates a Dictionary, adds some data to it and reads data back. 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Collections.Generic;

 

namespace DictionarySample

{

    class Program

    {

        static void Main(string[] args)

        {

           

            Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();

 

            AuthorList.Add("Mahesh Chand", 35);

            AuthorList.Add("Mike Gold", 25);

            AuthorList.Add("Praveen Kumar", 29);

            AuthorList.Add("Raj Beniwal", 21);

            AuthorList.Add("Dinesh Beniwal", 84);

 

            // Read all data

            Console.WriteLine("Authors List");

 

            foreach( KeyValuePair<string, Int16> author in AuthorList )

            {

                Console.WriteLine("Key = {0}, Value = {1}",

                    author.Key, author.Value);

            }

 

            Console.ReadKey();

 

        }

    }

}

 


Download Free Book
Download this free E-book: Programming Dictionary in C#



Properties 


The Count property gets the number of key/value pairs in a Dictionary. The following code snippet display number of items in a dictionary. 

 Console.WriteLine("Count: {0}", AuthorList.Count);

The Item property gets and sets the value associated with the specified key. The following code snippet sets and gets an items value. 

 // Set Item value 
AuthorList["Mahesh Chand"] = 20;
// Get Item value 
Int16 age = Convert.ToInt16(AuthorList["Mahesh Chand"]);


The Keys property gets a collection containing the keys in the Dictionary. It returns an object of KeyCollection type. The following code snippet reads all keys in a Dictionary.  

 // Get and display keys 
Dictionary<string, Int16>.KeyCollection keys = AuthorList.Keys;
foreach (string key in keys)
{
    Console.WriteLine("Key: {0}", key);
}


The Values property gets a collection containing the values in the Dictionary. It returns an object of ValueCollection type. The following code snippet reads all values in a Dictionary.  

 // Get and display values 
Dictionary<string, Int16>.ValueCollection values = AuthorList.Values;
foreach (Int16 val in values)
{
    Console.WriteLine("Value: {0}", val);
}

Summary

In this article, we learned how to use a dictionary in C#.


Download Free Book
Download this free E-book: Programming Dictionary in C# 


 

Login to add your contents and source code to this article
post comment
     

Hi Cristian Solervicens, You could also extend an article if it is related topic.Cheers!

Posted by Mahesh Chand Aug 12, 2012

Something important about flexibility of the Dictionary is that it accepts user defined classes as elements. class MyClass { public string atrib1 { get; set; } public int natrib { get; set; } } I can do MyClass Klase = new MyClass(); Dictionary<string, MyClass> Dict = new Dictionary<string, MyClass>(); Klase.atrib1 = "Primero"; Klase.natrib = 1; Dict.Add("Primero", Klase); //I Can acces the elements like this... "Secure Way" If don't exists, don't rise error. if (Dict.TryGetValue("Segundo", out Klase)) Console.WriteLine("EncontrĂ³ {0}, {1}", Klase.atrib1, Klase.natrib); //I Can acces the elements like this... "INSecure Way" If don't exists it rises an error. Console.WriteLine("EncontrĂ³ {0}, {1}", Dict["Segundo"].atrib1, Dict["Segundo"].natrib); //I can navigate through the Dictionary like this foreach (var p in Dict) { Console.WriteLine("Recorro {0}, {1}", p.Value.atrib1 , p.Value.natrib ); }

Posted by Cristian Solervicens Apr 08, 2011

Please post your question on the forums.

Posted by Mahesh Chand Mar 10, 2011

Dear Sir, i want your help regarding Singleton Pattern.. actually i m beginner programmer so i want to Create Multiple Objects in Singleton Pattern and restricted to 4 length...means after the creation of 4th object it will generate some error msg when user try to create 5th object...i still finding on the net but didn't find any example related to my problem ..i m very great thankful to you..if you make just simple program for me which resolve my problem ...

Posted by Shiraz Khan Mar 10, 2011
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.