Dictionary Methods in C#

CsharpProgrammingServer Side Programming

Dictionary is a collection of keys and values in C#. Dictionary<TKey, TValue> is included in the System.Collection.Generics namespace.

The following are the methods −

Sr.NoMethod & Description
1Add
Add key-value pairs in Dictionary
2Clear()
Remove all keys and values
3Remove
Removes the element with the specified key.
4ContainsKey
Checks whether the specified key exists in Dictionary<TKey, TValue>.
5ContainsValue
Checks whether the specified key value exists in Dictionary<TKey, TValue>.
6Count
Count the number of key-value pairs.
7Clear
Removes all the elements from Dictionary<TKey, TValue>.

Let us see how to add elements into a Dictionary and display the count.

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IDictionary<int, int> d = new Dictionary<int, int>();
      d.Add(1,97);
      d.Add(2,89);
      d.Add(3,77);
      d.Add(4,88);
      d.Add(5,78);
      d.Add(6,98);
      Console.WriteLine(d.Count);
   }
}

Output

6
raja
Published on 17-Sep-2018 13:27:00
Advertisements