DEV Community

Ishaan Sheikh
Ishaan Sheikh

Posted on • Edited on

6 3

C# Dictionary

The Dictionary in C# is a generic collection, which is used to store data in key-value pairs. It is available under the System.Collections.Generic namespace.

public class Dictionary<TKey,TValue>
Enter fullscreen mode Exit fullscreen mode

Parameters

TKey

It represents the data type of the key. For example, string, bool, int, etc.

TValue

It represents the data type of the value.

Creating a Dictionary

The Dictionary collection provides an Add() method to add elements to it.

...
using System.Collections.Generic;
...

static void Main(string[] args)
{
    Dictionary<int, string> users = new Dictionary<int, string>();
    users.Add(1, "John");
    users.Add(2, "Jane");
    users.Add(3, "Smith");
}
Enter fullscreen mode Exit fullscreen mode

Accessing an element

We can access the element from dictionary by providing the key inside [].

Console.WriteLine(users[1]); // John
Enter fullscreen mode Exit fullscreen mode

Removing an element

We can remove an element from the dictionary using the Remove method by providing the key to be removed.

users.Remove(2);
Console.Write(users.Count); // 2
Enter fullscreen mode Exit fullscreen mode

Iterating over the dictionary

We can use the foreach loop in C# to iterate over the dictionary collection.

foreach(KeyValuePair<int, string> user in users)
{
    Console.WriteLine(user.Key + " - " + user.Value);
}
Enter fullscreen mode Exit fullscreen mode

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (2)

Collapse
 
rafo profile image
Rafael Osipov

For cases your dictionary is being accessed from several threads use ConcurrentDictionary: docs.microsoft.com/en-us/dotnet/ap...

Collapse
 
frikishaan profile image
Ishaan Sheikh

Thanks for sharing!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay