Dictionary in C#

Dictionary in C#

Dictionary is a collection of key, value pairs.

Why is it important? Let look at one application?

In a city, many buildings are found. To find a structure we can search the entire city, street by street. But this becomes slow.

With a dictionary, we can map a building to a location. We can map “park” to where it is found. Then to find the park, we can skip searching the whole city.

To create in C# u need to System.Collections.Generic which contains the Dictionary Class. You can link a class to a dictionary. Like building class as value pairs.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<int, Building>  BuildingAll= new Dictionary<string, int>();

          BuildingAll.Add(1, "Castle", "Eden");
          BuildingAll.Add(2, "Dundin", "neworlean");
          BuildingAll.Add(3, "AucklandBuilding", "southpark");
          BuildingAll.Add(4, "HamitlonBuilding", "Storey");
    }
}

 public class Building {
  public int Id;
  public name string;
  public park string; 
}

Key value has to be unique. Otherwise, there will errors. You can iterate through the collections

foreach (var item in BuildingAll) {
 Console.Writeline("{0},{1}", item.Key, item.Value);
} 

or 
foreach (keyvaluepair<int,Building> pair in BuildingAll) {
Console.Writeline("{0},{1}", item.Key, item.Value);
}

You can check if the key is not unique then add new key

 

if (!BuildingAll.containsKey(5)) {
 BuildingAll.Add(5, "WellingtonBuilding", "den");
}

Quick lookup through the dictionary is using TrygetValue

 // Use inline "out string" with TryGetValue.
        if (BuildingAll.TryGetValue(5, "WellingtonBuilding")) {

}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *