C# Dictionary

What is Dictionary in C#?

In C#, Dictionary is a generic collection that is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is a generic type.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array
{
    class Program
    {
        static void Main(string[] args)
        {
            IDictionary<int, string> numberNames = new Dictionary<int, string>();
            numberNames.Add(1, "One"); //adding a key/value using the Add() method
            numberNames.Add(2, "Two");
            numberNames.Add(3, "Three");

            foreach (KeyValuePair<int, string> kvp in numberNames)
                Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value); //showing key,values

            Console.ReadLine();
        }
    }
}

Output

Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three


Write a comment


Name Email Message