Sunday, 25 December 2016

C# Dictionary

03:39 Posted by Nikesh , No comments

Dictionary class is a data structure which represents a collection of keys and values pair of data

this resides in name space using System.Collections.Generic;

Dictionary work faster than list collections because it indexes with key and value pair.

 key -- Value through which you want to use as a pointer  
Value -- This is which will give you result of that pointer.  
                  
Dictionary<key, value> capitals = new Dictionary<key, value>();

 
Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add("Assam", "Dispur");
capitals.Add("Bihar", "Patna");
capitals.Add("Goa", "Panaji");
capitals.Add("Haryana", "Chandigarh");




Calling:

Getting Result Directly By Indexing


string capitalResult = capitals["Goa"];

This will result captialResult = "Panji"


Using Dictionary with classes:




public class State
{
    public string Capital {get; set;}
    public int Educations {get; set;}
    public int Size  {get; set;}


   public State(string capital, int educ, int size)
   {
       Capital = capital;
       Population = pop;
       Size = size;
    }


Method which bind objects to dictionary

          
    public static Dictionary<string, State> GetStates()

      {                   //Referencing State Class
     var states = new Dictionary<string,State>();
     var myState1 = new State("Dispur",1234567,123);
      states.Add("Asam", mystate1)
     var myState2 = new State("Banglore",1234567,123);
      states.Add("Bihar", mystate2)
       };

}
   
Calling Part...

we can call it as

  var stateResult = State.GetStates();

  string capitalofBihar = stateResult["Bihar"].Capital;

Result:-  "Banglore".


Above are simple steps for working with dictionary.

Working Objects with List<object>


State st1 = new State(){State="Banglore",Capital="Patna",Educations = 12345,Size=123}

State st2 = new State(){State="Asam",Capital="Dispur",Educations = 12345,Size=123}
State st3 = new State(){State="Goa",Capital="Punji",Educations = 12345,Size=123}

List<State> listStates = new List<State>();
listStates.Add(st1);
listStates.Add(st2);
listStates.Add(st3);


Calling Part...



  State result = listStates.Find(state => state.Capital == capitalnamevalue);
     if(result == null)
       {
          ...do whatever you want
       }
   else{

       result.State,result.Capital,result.Size;
       }


   

For Indexing we can also bind object attributes in dictionary based on its type and make indexing fast.

Dictionary<string, string> capitals = new Dictionary<string, string>();
capitals.Add(st1.Capital, "Dispur");
capitals.Add(st2.Capital, "Patna");
capitals.Add(st3.Capital, "Panaji");
capitals.Add(st4.Capital, "Chandigarh");


0 comments:

Post a Comment