How to create a Dictionary using 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.

To create a dictionary, you first need to set it and add the key and values. Here we have added 5 keys with values to a Dictionary. We have set its keys and value type as int.

IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,44);
d.Add(2,34);
d.Add(3,66);
d.Add(4,47);
d.Add(5,76);

The following is the complete code −

Example

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      IDictionary<int, int> d = new Dictionary<int, int>();
      d.Add(1,44);
      d.Add(2,34);
      d.Add(3,66);
      d.Add(4,47);
      d.Add(5,76);

      Console.WriteLine(d.Count);
   }
}
raja
Published on 13-Aug-2018 14:00:04
Advertisements