SIGN UP MEMBER LOGIN:    
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;

 

Add and Read Data


As other collection classes, the Dictionary class has Add, Remove, RemoveAt 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();

 

        }

    }

}

 

Summary

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


 

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

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
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor