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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay