DEV Community

loading...

C# Dictionary

Ishaan Sheikh
Software Engineer with a passion for building things đŸ’ģ🤓
Originally published at frikishaan.com ãƒģ1 min read

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

Discussion (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
sheikh_ishaan profile image
Ishaan Sheikh Author

Thanks for sharing!