Dictionary in C#

Methods and Attributes in C#


Declaration in C#

A Dictionary can be declared as follows.

// If capacity of dictionary is not known
Dictionary<string, string> dicObj = new Dictionary<string, string>();
// If capacity of dictionary is known
Dictionary<string, string> dicObj = new Dictionary<string, string>(5);

Add() in C#

This method is used to add elements with key-value pairs in the dictionary object.

DicObj.Add("key1", "val1");
DicObj.Add("key2", "val2");
DicObj.Add("key3", "val3");
DicObj.Add("key4", "val4");

Reading or iterating through Dictionary element

Since the Dictionary type represents a collection, we can use the foreach loop to go through all the items and read them using the Key and Value properties.

foreach (KeyValuePair<string, Int16> author in AuthorList)
{
    Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
}

Remove() in C#

This method is used to remove an element from a dictionary object.

DicObj.Remove("key4");

Clear() in C#

This method removes all the elements from a dictionary object.

DicObj.Clear();

ContainsKey() in C#

This method is used to find a key from the Dictionary and it returns a Boolean value indicating whether that key is found in the collection or not.

if (!AuthorList.ContainsKey("key4"))
{
    DicObj["key4"] = 20;
}

ContainsValue() in C#

This method is used to check whether a value exists in the dictionary or not and it returns a Boolean value indicating whether that value is found in the collection or not.

if (!AuthorList.ContainsValue("Value4"))
{
    // write code here
}

Keys in C#

This attribute returns a collection of keys present in the dictionary object. It returns an object of KeyCollection type.

Dictionary<string, string>.KeyCollection keys = DicObj.Keys;
foreach (string key in keys)
{
    // code to process keys
}

Values in C#

This attribute returns a collection of values present in the dictionary object. It returns an object of ValueCollection type.

Dictionary<string, string>.ValueCollection values = DicObj.Values;
foreach (string val in values)
{
    // code to process values
}

Item in C#

The Item property is used to get and set the value associated with the specified key.

// Set Item value
DicObj["key4"] = value5;
// Get Item value
string value = DicObj["key4"];

Count in C#

This property is used to count the number of elements present in the dictionary at any time.

int noOfElements = DicObj.Count;