Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » Dictionary in C#

Dictionary in C#

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#.

Author Rank :
Page Views : 21750
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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#.

CopyLegalTracker.gif

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Hiii Sir by Shiraz On March 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 ...
Reply | Email | Modify 
Re: Hiii Sir by Mahesh On March 10, 2011
Please post your question on the forums.
Reply | Email | Modify 
Important about flexibility by Cristian On April 8, 2011
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 ); }
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.