Wednesday, October 27, 2010

Working with the Generic Dictionary Class In C#

This Example Demonstrates the use Of a Generic Dictionary Class Which is an Improved HashTable Class and performs much better than a HashTable.

Example :


using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary< int, string > students = new Dictionary< int, string >();
students.Add(1, "Hefin");
students.Add(2, "Abbas");
students.Add(3, "Rinso");
students.Add(4, "Sachin");

Dictionary< string, string > Employees = new Dictionary< string, string >();
Employees.Add("E01", "Hefin Dsouza");
Employees.Add("E02", "Abbas Electriwala");
Employees.Add("E03", "Rinso Joseph");
Employees.Add("E04", "Sachin Gaikar");

Console.WriteLine("List of all Students");
foreach (KeyValuePair< int,string > n in students)
{
Console.WriteLine("|Roll Number : " + n.Key + "t| Name : " + n.Value);
}

Console.WriteLine("List of all Employees");
foreach (KeyValuePair< string, string > n in Employees)
{
Console.WriteLine("|EMP ID : " + n.Key + "tt| EMP Name : " + n.Value);
}
}
}

This is an Improved HashTable which restricts what data type will the Key be and What Data Type the value should be.So it makes this class much Type Safe.

No comments:

Post a Comment