Collections-Dictionary - DotNet and DataBase

Thursday, 19 July 2018

Collections-Dictionary




In C#, Dictionary is one type of collection which stores data in Key,Value pair format. Here Key is a unique which doesn't allow duplicate values. By the help of key we can search manipulate the collection. Dictionary derived from System.Collections.Generic

Syntax:
Dictionary<datatypedatatype> <variable name> = new Dictionary<datatypedatatype>();

Using foreach loop we can fetch the elements in the collection.
Dictionary is type safe. It doesn't allow to insert the elements which are other than the types defined on declaration.

Example:
Dictionary<intstring> <variable name> = new Dictionary<intstring>();
Dictionary<stringstring> <variable name> = new Dictionary<stringstring>();


using System;
using System.Collections.Generic;
     
class ClassDisctionary
    {
        public void DictionaryMethod()
        {
            Dictionary<int, string> dc = new Dictionary<int, string>();
            dc.Add(1, "C#");
            dc.Add(2, "ASP");
            dc.Add(3, "MVC");
            dc.Add(4, "SQL Server");
            dc.Add(5, "Java");
            dc.Add(6, "MySQL");

            foreach (KeyValuePair<int,string> item in dc)
            {
                 int a = item.Key;
                Console.WriteLine("Employee ID = "+item.Key+" Employee Name = "+item.Value);
            }
        }
    }
public class Program
{
 public static void Main()
 {
    ClassDisctionary c = new ClassDisctionary();
            c.DictionaryMethod();
 }
}

Output:
Employee ID = 1 Employee Name = C#
Employee ID = 2 Employee Name = ASP
Employee ID = 3 Employee Name = MVC
Employee ID = 4 Employee Name = SQL Server
Employee ID = 5 Employee Name = Java
Employee ID = 6 Employee Name = MySQL


Practice

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.