A dictionary is a data structure in C# that is similar to the hash-table (a collection used to store key-value
pairs). In a dictionary, we cannot have duplicate or null keys
, but we can have duplicate or null values
.
The first argument specifies the key type and the second is for the value type.
Dictionary <dataType, dataType> dictionary = new Dictionary<dataType, dataType>();
Remember: Dictionary collection is implemented in the class
System.Collection.Generics
.
Method | Description |
---|---|
1.Add(key, value) |
Used to insert a key-value pair in a dictionary. |
2.Remove(key) |
Used to remove a pair with a specified key. |
3.ConatinsKey(key) |
Used to check whether or not a specified key exists in the dictionary. |
4.ConatinsValue(value) |
Used to check whether or not a specified value exists in the dictionary. |
5.Clear() |
Used to remove all the pairs from the dictionary. |
using System;using System.Collections.Generic;class DictionaryTesting{static void Main(){Dictionary<int, string> dictionary = new Dictionary<int, string>();// Add(key, value) Methoddictionary.Add(1,"John");dictionary.Add(2,"Cassy");dictionary.Add(3,"Peter");dictionary.Add(4,"Luis");dictionary.Add(5,"Flash");// Printing dictionarySystem.Console.WriteLine("Dictionary after adding pair:");foreach(KeyValuePair<int, string> temp in dictionary){Console.WriteLine("Key {0} and Value {1}", temp.Key, temp.Value);}// Remove(key) Methoddictionary.Remove(4);// Printing dictionarySystem.Console.WriteLine("Dictionary after removing pair with key 4:");foreach(KeyValuePair<int, string> temp in dictionary){Console.WriteLine("Key {0} and Value {1}", temp.Key, temp.Value);}// ConatinsKey(key) MethodSystem.Console.WriteLine("Dictionary has any pair with the key = 5?");System.Console.WriteLine(dictionary.ContainsKey(5));}}
Free Resources