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>

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

Accessing an element

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

Console.WriteLine(users[1]); // John

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

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

8