The Dictionary is related to System.Collections.Generic namespace. Dictionary contains on key-value pairs. Where each key is associated with a unique value. Dictionary can store specific type value for example if you are making a dictionary of int type then it can only store integer type values. On other hand hashtable can store any data type value.
You need to import the System.Collections.Generic namespace to work with a Dictionary. To create a Dictionary, you can use the following code:
You can add key-value pairs to a Dictionary using the Add method or by using the indexer:
// inserting fruit items in key-value pair
// inserting fruit items in key-value pair
// inserting fruit items in key-value pair
// inserting fruit items in key-value pair
You can retrieve values from the Dictionary using their associated keys:
// Returns 20
// Returns Violet
// Returns 20
// Returns Violet
You can check if a key exists in the Dictionary using the ContainsKey method:
// Returns true
// Returns true
// Returns true
// Returns true
You can use a foreach loop or LINQ to iterate through the key-value pairs in a Dictionary:
You can remove key-value pairs from the Dictionary using the Remove method:
You can find the number of key-value pairs in the Dictionary using the Count property:
Dictionary is collection of Key-Value pairs. In Key-Value pairs, each key must be unique. Dictionary can store specific type (int, float, string, bool) of data.