19
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>
It represents the data type of the key. For example, string, bool, int, etc.
It represents the data type of the value.
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");
}
We can access the element from dictionary by providing the key inside []
.
Console.WriteLine(users[1]); // John
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
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);
}
19