.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# Dictionary
C# Dictionary class uses the concept of hashtable. It stores values on the basis of key. It contains unique keys only. By the help of key, we can easily search or remove elements. It is found in System.Collections.Generic namespace.
C# Dictionary example
Let's see an example of generic Dictionary class that stores elements using Add() method and iterates elements using for-each loop. Here, we are using KeyValuePair class to get key and value.
using System;
using System.Collections.Generic;
public class DictionaryExample
{
public static void Main(string[] args)
{
Dictionary names = new Dictionary();
names.Add("1","Sunil");
names.Add("2","Anil");
names.Add("3","Mathew");
names.Add("4","Pushkar");
foreach (KeyValuePair kv in names)
{
Console.WriteLine(kv.Key+" "+kv.Value);
}
}
}
using System.Collections.Generic;
public class DictionaryExample
{
public static void Main(string[] args)
{
Dictionary names = new Dictionary();
names.Add("1","Sunil");
names.Add("2","Anil");
names.Add("3","Mathew");
names.Add("4","Pushkar");
foreach (KeyValuePair kv in names)
{
Console.WriteLine(kv.Key+" "+kv.Value);
}
}
}
Output:
1 Sunil
2 Anil
3 Mathew
4 Puskar
2 Anil
3 Mathew
4 Puskar