Member-only story
C# Dictionary With Examples

The Dictionary is related to System.Collections.Generic namespace. Dictionary contains on key-value pairs. Where each key is associated with a unique value. Dictionary can store specific type value for example if you are making a dictionary of int type then it can only store integer type values. On other hand hashtable can store any data type value.
Features with dictionary in C#:
Creating a Dictionary:
You need to import the System.Collections.Generic namespace to work with a Dictionary. To create a Dictionary, you can use the following code.
using System;
using System.Collections.Generic;
Dictionary<string,int> dictfruitprices = new Dictionary<string,int>();
Dictionary<string,string> dictfruitnames = new Dictionary<string,string>();
Adding Key-Value Pairs:
You can add key-value pairs to a Dictionary using the Add method or by using the indexer.
dictfruitprices.Add("Apple",16);
dictfruitprices.Add("Orange",12);
dictfruitprices.Add("Cherry",18);
dictfruitprices["Papaya"] = 20;
dictfruitprices["Grape"] = 6;
dictfruitnames.Add("Apple","Red");
dictfruitnames.Add("Mango","Yellow");
dictfruitnames.Add("Cherry","Red");
dictfruitnames.Add("Orange","Dark Orange");
dictfruitnames["Grape"] = "Violet";
dictfruitnames.["Kiwi"] = "Spring Green";
Accessing Values
You can retrieve values from the Dictionary using their associated keys.
int fruitprice = dictfruitprices["Papaya"]; // Returns 20
int fruitcolor = dictfruitnames["Grape"]; // Returns Violet
Checking for Key Existence
You can check if a key exists in the Dictionary using the ContainsKey method
bool containsAlice = dictfruitprices.ContainsKey("Papaya"); // Returns true
bool containsAlice = dictfruitnames.ContainsKey("Grape"); // Returns true
Iterating through a Dictionary
You can use a foreach loop or LINQ to iterate through the key-value pairs in a Dictionary.
foreach (var item1 in dictfruitprices)
{
Console.WriteLine($"{item1.Key}: {item1.Value}");
{…