Introduction About Dictionary in c# :
- Dictionary is collection of (Key, Value) pairs.
- Dictionary class is present in System.Collections.Generic namespaces.
- When creating Dictionary, we should specify the type for key and value.
- Dictionary provides fast lookup for values using keys.
- Keys in Dictionary must be unique.
i will Explaining With Example Code . First we Should open Visual Studio and choose Console Application.
Go to File -> New -> Project-> Visual C# -> Console Application.

my console application name called as Dictionary. I have Student Class with Id,Name,Salary auto implemented property. Let's also create Student object for Student Class in main Method . I called as object Student 1 and initialize Property with values.i crate two more Sudent class object .The object must be unique .finally i created Student Dictionary . Dictionary class present in collections.Generic Namespace .
- using System.Collections.Generic;
- namespace Dictionary
- {
- class Program
- {
- static void Main(string[] args)
- {
- Student Student1 = new Student()
- {
- Id = 1,
- Name = "Thennarasu",
- Salary = 25000
- };
- Student Student2 = new Student()
- {
- Id = 2,
- Name = "Karthi",
- Salary = 35000
- };
- Student Student3 = new Student()
- {
- Id = 3,
- Name = "Mano",
- Salary = 45000
- };
- Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();
- StudentDictionary.Add(Student1.Id, Student1);
- StudentDictionary.Add(Student2.Id, Student2);
- StudentDictionary.Add(Student3.Id, Student3);
- }
- }
- public class Student
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public int Salary { get; set; }
- }
- }
when Create Dictionary we need to Specify datatype key and value.


For key in this Dictionary .i used key value Student ID and value customer . we used To Add Keyword to add objects to Dictionary.we added all objects Student Id and value objects.
- Dictionary<int, Student> StudentDictionary = new Dictionary<int, Student>();
- StudentDictionary.Add(Student1.Id, Student1);
- StudentDictionary.Add(Student2.Id, Student2);
- StudentDictionary.Add(Student3.Id, Student3);
- Student StudentID3 =StudentDictionary[3];
- Console.WriteLine("StudentID={0},StudentName={1},StudentSalary={2}", StudentID3.Id,StudentID3.Name,StudentID3.Salary);
- Console.ReadLine();
Next Going to Display all result using for each loop. we use Keyvaluepair Because Dictionary collections of key and value . foreach loop keyvaluepair we should mention Tkey and Tvalue. in our Code we use Tkey using StudentId and Tvalue using Student.
- foreach(KeyValuePair<int,Student> StudentKeyvaluepair in StudentDictionary)
- {
- Console.WriteLine("Key={0}", StudentKeyvaluepair.Key);
- Student stud = StudentKeyvaluepair.Value;
- Console.WriteLine("Student Id={0}, Student Name={1},Student Salary={2}", stud.Id, stud.Name, stud.Salary);
- Console.ReadKey();
- }


Comments
Join the conversation! Your thoughts help the community grow.