HashMap in C# (Dictionary)

For C# programs, they typically use a Dictionary as a collection of key-value pairs instead of HashMap, which is commonly used in Java programs. However, the functionality of HashMap in Java can still be achieved in C# using Dictionary.

Following are some of the common methods used in C# HashMap:

Add():

This method adds a new key-value pair to the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue");

Remove():

This method removes the specified key-value pair from the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); hashMap.Remove(1);

ContainsKey():

This method checks if a specific key is present in the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); bool containsKey = hashMap.ContainsKey(1);

ContainsValue():

This method checks if a specific value is present in the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); bool containsValue = hashMap.ContainsValue("red");

Clear():

This method removes all key-value pairs from the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); hashMap.Clear();

Count:

This property returns the number of key-value pairs in the HashMap.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); int count = hashMap.Count;

TryGetValue():

This method tries to get the value associated with the specified key, and returns a boolean to indicate whether the operation was successful or not.

Dictionary<int, string> hashMap = new Dictionary<int, string>(); hashMap.Add(1, "red"); hashMap.Add(2, "blue"); string value; bool success = hashMap.TryGetValue(1, out value);

These are some of the common methods used in C# HashMap (Dictionary). By using these methods, you can easily add, remove, check for the existence of keys and values, clear the collection, count the number of items, and get the value associated with a key in the HashMap.