-
- Dictionary<string, string> dicObj = new Dictionary<string, string>();
-
-
- Dictionary<string, string> dicObj = new Dictionary<string, string>(5);
2. Add()
This method is used to add elements with key value pair in the dictionary object.
- DicObj.Add("key1", "val1");
- DicObj.Add("key2", " val2");
- DicObj.Add("key3", " val3");
- DicObj.Add("key4", " val4");
3. Reading or iterating through Dictionary element
Since the Dictionary type represents a collection so we can use the foreach loop to go through all the items and read them using they Key and Value properties.
- foreach (KeyValuePair<string, Int16> author in AuthorList)
- {
- Console.WriteLine("Key: {0}, Value: {1}", author.Key, author.Value);
- }
4. Remove()
This method is used to remove an element from a dictionary object.
5. Clear()
This method removes all the elements from a dictionary object.
6. ContainsKey()
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;
- }
7. ContainsValue()
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"))
- {
-
- }
8. Keys
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)
- {
-
- }
9. Values
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)
- {
-
- }
10. Item
The Item property is used to get and set the value associated with the specified key.
-
- DicObj ["key4"] = value5;
-
- string value = DicObj ["key4];
11. Count
This property is used to count the number of elements present in the dictionary at any time.
- Int noOfElements = DicObj.Count