SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
Programming Dictionary in C#

This free book is provided by courtesy of C# Corner, Mindcracker Network and its
authors. Feel free to share this book with your friends and co-workers. Please do not
reproduce, republish, edit or copy this book.




Mahesh Chand

July 2012, Garnet Valley PA




                                          ©2012 C# Corner.
           SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Introduction
A dictionary type represents a collection of keys and values pair of data.

The Dictionary class defined in the System.Collections.Generic namespace is a generic class and can
store any data types in a form of keys and values. Each key must be unique in the collection. Before you
use the Dictionary class in your code, you must import the System.Collections.Generic namespace using
the following line.
using System.Collections.Generic;

Creating a Dictionary
The Dictionary class constructor takes a key data type and a value data type. Both types are generic so it
can be any .NET data type.

The following The Dictionary class is a generic class and can store any data types. This class is defined in
the code snippet creates a dictionary where both keys and values are string types.

Dictionary<string, string> EmployeeList = new Dictionary<string, string>();

The following code snippet adds items to the dictionary.

EmployeeList.Add("Mahesh Chand", "Programmer");
EmployeeList.Add("Praveen Kumar", "Project Manager");
EmployeeList.Add("Raj Kumar", "Architect");
EmployeeList.Add("Nipun Tomar", "Asst. Project Manager");
EmployeeList.Add("Dinesh Beniwal", "Manager");

The following code snippet creates a dictionary where the key type is string and value type is short
integer.

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

The following code snippet adds items to the dictionary.

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);

We can also limit the size of a dictionary. The following code snippet creates a dictionary where the key
type is string and value type is float and total number of items it can hold is 3.

Dictionary<string, float> PriceList = new Dictionary<string, float>(3);


                                            ©2012 C# Corner.
             SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The following code snippet adds items to the dictionary.

PriceList.Add("Tea", 3.25f);
PriceList.Add("Juice", 2.76f);
PriceList.Add("Milk", 1.15f);

Reading Dictionary Items
The Dictionary is a collection. We can use the foreach loop to go through all the items and read them
using they Key ad Value properties.

foreach (KeyValuePair<string, Int16> author in AuthorList)
{
 Console.WriteLine("Key: {0}, Value: {1}",
 author.Key, author.Value);
}

The following code snippet creates a new dictionary and reads all of its items and displays on the
console.
public void CreateDictionary()
{
    // Create a dictionary with string key and Int16 value pair
    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);
    }
}


Dictionary Properties
The Dictionary class has three properties – Count, Keys and Values.

Count
The Count property gets the number of key/value pairs in a Dictionary.

The following code snippet display number of items in a dictionary.



                                            ©2012 C# Corner.
             SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Console.WriteLine("Count: {0}", AuthorList.Count);


Item
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"]);

Keys
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);
}



Values
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);
}



Dictionary Methods
The Dictionary class is a generic collection and provides all common methods to add, remove, find and
replace items in the collection.

Add Items



                                            ©2012 C# Corner.
             SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
The Add method adds an item to the Dictionary collection in form of a key and a value.

The following code snippet creates a Dictionary and adds an item to it by using the Add method.

Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>();
AuthorList.Add("Mahesh Chand", 35);

Alternatively, we can use the Item property. If the key does not exist in the collection, a new item is
added. If the same key already exists in the collection, the item value is updated to the new value.

The following code snippet adds an item and updates the existing item in the collection.

AuthorList["Neel Beniwal"] = 9;
AuthorList["Mahesh Chand"] = 20;

Remove Item

The Remove method removes an item with the specified key from the collection. The following code
snippet removes an item.

// Remove item with key = 'Mahesh Chand'
AuthorList.Remove("Mahesh Chand");

The Clear method removes all items from the collection. The following code snippet removes all items
by calling the Clear method.

// Remove all items
AuthorList.Clear();



Find a Key

The ContainsKey method checks if a key is already exists in the dictionary. The following code snippet
checks if a key is already exits and if not, add one.

if (!AuthorList.ContainsKey("Mahesh Chand"))
{
    AuthorList["Mahesh Chand"] = 20;
}



Find a Value

The ContainsValue method checks if a value is already exists in the dictionary. The following code
snippet checks if a value is already exits.

if (!AuthorList.ContainsValue(9))
{


                                            ©2012 C# Corner.
             SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
Console.WriteLine("Item found");
}
Sample

Here is the complete sample code showing how to use these methods.

// Create a dictionary with string key and Int16 value pair
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);

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

// Set Item value
AuthorList["Neel Beniwal"] = 9;

if (!AuthorList.ContainsKey("Mahesh Chand"))
{
    AuthorList["Mahesh Chand"] = 20;
}
if (!AuthorList.ContainsValue(9))
{
    Console.WriteLine("Item found");
}

// Read all items
Console.WriteLine("Authors all items:");

foreach (KeyValuePair<string, Int16> author in AuthorList)
{
    Console.WriteLine("Key: {0}, Value: {1}",
        author.Key, author.Value);
}

// Remove item with key = 'Mahesh Chand'
AuthorList.Remove("Mahesh Chand");


// Remove all items
AuthorList.Clear();




                                           ©2012 C# Corner.
            SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.

Weitere ähnliche Inhalte

Ähnlich wie Dictionary e book

Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-convertedMicheal Ogundero
 
C# Dictionary Hash Table and sets
C# Dictionary Hash Table and setsC# Dictionary Hash Table and sets
C# Dictionary Hash Table and setsSimplilearn
 
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyone
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyoneAnnotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyone
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyonePronovix
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxjchandrasekhar3
 
Building DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchBuilding DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchEelco Visser
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
Net framework session02
Net framework session02Net framework session02
Net framework session02Vivek chan
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleMongoDB
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4DEVCON
 

Ähnlich wie Dictionary e book (20)

Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-converted
 
C# Dictionary Hash Table and sets
C# Dictionary Hash Table and setsC# Dictionary Hash Table and sets
C# Dictionary Hash Table and sets
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
 
First approach in linq
First approach in linqFirst approach in linq
First approach in linq
 
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyone
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyoneAnnotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyone
Annotate, Automate & Educate: Driving generated OpenAPI docs to benefit everyone
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
 
Mongo DB Presentation
Mongo DB PresentationMongo DB Presentation
Mongo DB Presentation
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Building DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language WorkbenchBuilding DSLs with the Spoofax Language Workbench
Building DSLs with the Spoofax Language Workbench
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
Amusing C#
Amusing C#Amusing C#
Amusing C#
 
Collection
CollectionCollection
Collection
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Apache Lucene Basics
Apache Lucene BasicsApache Lucene Basics
Apache Lucene Basics
 
Net framework session02
Net framework session02Net framework session02
Net framework session02
 
Fast track to lucene
Fast track to luceneFast track to lucene
Fast track to lucene
 
Indexing Strategies to Help You Scale
Indexing Strategies to Help You ScaleIndexing Strategies to Help You Scale
Indexing Strategies to Help You Scale
 
Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4Python Code Camp for Professionals 4/4
Python Code Camp for Professionals 4/4
 

Kürzlich hochgeladen

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 

Kürzlich hochgeladen (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 

Dictionary e book

  • 1. Programming Dictionary in C# This free book is provided by courtesy of C# Corner, Mindcracker Network and its authors. Feel free to share this book with your friends and co-workers. Please do not reproduce, republish, edit or copy this book. Mahesh Chand July 2012, Garnet Valley PA ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
  • 2. Introduction A dictionary type represents a collection of keys and values pair of data. The Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection. Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line. using System.Collections.Generic; Creating a Dictionary The Dictionary class constructor takes a key data type and a value data type. Both types are generic so it can be any .NET data type. The following The Dictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types. Dictionary<string, string> EmployeeList = new Dictionary<string, string>(); The following code snippet adds items to the dictionary. EmployeeList.Add("Mahesh Chand", "Programmer"); EmployeeList.Add("Praveen Kumar", "Project Manager"); EmployeeList.Add("Raj Kumar", "Architect"); EmployeeList.Add("Nipun Tomar", "Asst. Project Manager"); EmployeeList.Add("Dinesh Beniwal", "Manager"); The following code snippet creates a dictionary where the key type is string and value type is short integer. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>(); The following code snippet adds items to the dictionary. 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); We can also limit the size of a dictionary. The following code snippet creates a dictionary where the key type is string and value type is float and total number of items it can hold is 3. Dictionary<string, float> PriceList = new Dictionary<string, float>(3); ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
  • 3. The following code snippet adds items to the dictionary. PriceList.Add("Tea", 3.25f); PriceList.Add("Juice", 2.76f); PriceList.Add("Milk", 1.15f); Reading Dictionary Items The Dictionary is a collection. We can use the foreach loop to go through all the items and read them using they Key ad Value properties. foreach (KeyValuePair<string, Int16> author in AuthorList) { Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value); } The following code snippet creates a new dictionary and reads all of its items and displays on the console. public void CreateDictionary() { // Create a dictionary with string key and Int16 value pair 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); } } Dictionary Properties The Dictionary class has three properties – Count, Keys and Values. Count The Count property gets the number of key/value pairs in a Dictionary. The following code snippet display number of items in a dictionary. ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
  • 4. Console.WriteLine("Count: {0}", AuthorList.Count); Item 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"]); Keys 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); } Values 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); } Dictionary Methods The Dictionary class is a generic collection and provides all common methods to add, remove, find and replace items in the collection. Add Items ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
  • 5. The Add method adds an item to the Dictionary collection in form of a key and a value. The following code snippet creates a Dictionary and adds an item to it by using the Add method. Dictionary<string, Int16> AuthorList = new Dictionary<string, Int16>(); AuthorList.Add("Mahesh Chand", 35); Alternatively, we can use the Item property. If the key does not exist in the collection, a new item is added. If the same key already exists in the collection, the item value is updated to the new value. The following code snippet adds an item and updates the existing item in the collection. AuthorList["Neel Beniwal"] = 9; AuthorList["Mahesh Chand"] = 20; Remove Item The Remove method removes an item with the specified key from the collection. The following code snippet removes an item. // Remove item with key = 'Mahesh Chand' AuthorList.Remove("Mahesh Chand"); The Clear method removes all items from the collection. The following code snippet removes all items by calling the Clear method. // Remove all items AuthorList.Clear(); Find a Key The ContainsKey method checks if a key is already exists in the dictionary. The following code snippet checks if a key is already exits and if not, add one. if (!AuthorList.ContainsKey("Mahesh Chand")) { AuthorList["Mahesh Chand"] = 20; } Find a Value The ContainsValue method checks if a value is already exists in the dictionary. The following code snippet checks if a value is already exits. if (!AuthorList.ContainsValue(9)) { ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.
  • 6. Console.WriteLine("Item found"); } Sample Here is the complete sample code showing how to use these methods. // Create a dictionary with string key and Int16 value pair 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); // Count Console.WriteLine("Count: {0}", AuthorList.Count); // Set Item value AuthorList["Neel Beniwal"] = 9; if (!AuthorList.ContainsKey("Mahesh Chand")) { AuthorList["Mahesh Chand"] = 20; } if (!AuthorList.ContainsValue(9)) { Console.WriteLine("Item found"); } // Read all items Console.WriteLine("Authors all items:"); foreach (KeyValuePair<string, Int16> author in AuthorList) { Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value); } // Remove item with key = 'Mahesh Chand' AuthorList.Remove("Mahesh Chand"); // Remove all items AuthorList.Clear(); ©2012 C# Corner. SHARE THIS DOCUMENT AS IT IS. DO NOT REPRODUCE, REPUBLISH, CHANGE OR COPY.