C Sharp Dictionary Code Examples

Last Updated On Wednesday 12th Jan 2022

C# dictionary

  • Similar to a hashtable, a dictionary will store its value in a key-value pair.
  • We can then use the key to retrieve the value.

Defining a Dictionary CSharp

  • From the Microsoft Documentation the Dictionary is defined like the below code.
	Dictionary<TKey, TValue>()
	
  • Need to specify the types of both our keys and values in the declaration.
  • We have a lot of flexibility but not the flexibility that we had in a hash table.
	 Dictionary<int, string> myDictionary = new Dictionary<int, string>();
	
  • In Above Code, the key will be of type integer, and the value will be of type string

  • To use dictionaries, we need to include the below code.

	using System.Collection.Generics;
	
  • If you want to Add Elements in your Dictionary, then use the Add() method to add key/value pairs in your Dictionary
	myDictionary.Add(1, "Hello");
	

dictionary c# example

	using System;
using System.Collections.Generic;

class DictionaryTest {
  static public void Main() {
    Dictionary < string, double > myDict = new Dictionary < string, double > ();

    myDict.Add("#1", 111);
    myDict.Add("#2", 222);
    myDict.Add("#3", 333);

    if (myDict.ContainsKey("#2")) {
      double value = myDict["#2"];
      Console.WriteLine(value);
    }
  }
}

// 222

	

c# dictionary example

	using System;
using System.Collections.Generic;

class DictionaryTest {
  static public void Main() {
    Dictionary < int, string > books = new Dictionary < int, string > ();

    books.Add(1, "The Paper Palace: A Novel");
    books.Add(2, "Things Fall Apart");
    books.Add(3, "The Handmaid's Tale: The Graphic Novel");

    Dictionary < string, object > user = new Dictionary < string, object > () {
      {
        "id",
        1
      }, {
        "name",
        "Adam"
      }, {
        "age",
        21
      }
    };
    Console.Write(books[1]);
    Console.WriteLine("\n");
    Console.Write(user["name"]);
  }
}
// The Paper Palace: A Novel

// Adam