Home » C# » C# Dictionary – select key value pair

C# Dictionary – select key value pair

By Emily

Key value pairs pop up everywhere in C# code, and yet after twenty years of being a software developer I still find myself Googling ‘C# how to get a value from a key value pair‘ on a regular basis whenever I am working with a C# Dictionary. In this post I’ll explain how to initialize a C# Dictionary, how to add an item to a C# Dictionary, how to select an item, and how to get a value from a key value pair in a Dictionary.

How to initialize a C# Dictionary

Firstly you need to initialize a Dictionary and put some data in it – and in this post I’ll be talking about a dictionary of drinks data, to create a drinks order 🙂 Please note, I’ve also written a similar post but using a C# List instead of a Dictionary.

We initialize a Dictionary where the key is an integer and the value is a string :

using System.Collections.Generic;

Dictionary<int, string> drinksOrder = new Dictionary<int, string>()
{
	{ 100, "Lemonade"},
	{ 203, "Gin and tonic" },
	{ 145, "Small white wine"},
	{ 701, "Coke" },
	{ 361, "Orange juice" }
};

How to add to a C# Dictionary

To add another key value pair to the Dictionary :

drinksOrder.Add(487, "Sparkling water");

C# Dictionary get value from a key value pair

To get a value from the Dictionary using the key, is as simple as using the pattern dictionaryName[key]. So in this case to select the value “Orange juice” from the C# Dictionary we would use this code:

//get value out using the key
var drinkValue = drinksOrder[361];

//now write this to the console
Console.WriteLine("Get Drink using key > " + drinkValue);

//this prints - 
Get Drink using key > Orange juice

However in reality you need to add a little more code to deal with what happens if the key does not exist in the Dictionary. In the code above, an error will be thrown. This is how to check if the key exists first:

//check if the Dictionary contains the key
if (barOrder.ContainsKey(361))
{
 	 //it dies exist, so we can safely use the value
     selectedDrink = barOrder[361];
}

So in a C# dictionary to get a value by key you first check if the Dictionary contains the key, and then you get the value.

How to convert a Dictionary Key Value pair into JSON

If you want to serialize your Dictionary into json, or a key value pair into json, you need to use the Newtonsoft Nuget package like this:

using Newtonsoft.Json;

var json = JsonConvert.SerializeObject(barOrder);

I’ve put together a simple Console app that uses much of this code refactored into stand alone methods. It includes examples of how to :

  1. Initialize a Dictionary
  2. Add an item to a Dictionary
  3. Remove an item from a Dictionary
  4. Clear a Dictionary
  5. Convert a Dictionary to json
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //create the initial drinks order
            var barOrder = InitializeDictionary();
            WriteDictionary(barOrder);
            
            //someone cancels their drink
            Console.WriteLine("\nRemove drink by key ....");
            barOrder.Remove(145);

            //write the order again
            WriteDictionary(barOrder);
            
            //someone wants to add a couple of drinks to the order
            AddDrinks(barOrder);
            WriteDictionary(barOrder);

            //checks if the Dictionary contains certain keys, and gets the
            //value if it does
            CheckDrinks(barOrder);
            WaitForKeyPress();

            //converts the dictionary to json
            Console.WriteLine("\nConvert the order to json ....");
            var json = JsonConvert.SerializeObject(barOrder);
            Console.WriteLine(json);

            //now clear the order because we are finished
            Console.WriteLine("\nNow clear the order because is's complete....");
            barOrder.Clear();

            //write the order again
            WriteDictionary(barOrder);
        }

        private static void WaitForKeyPress()
        {
            Console.WriteLine("Press any key to continue....");
            Console.ReadKey();
        }

        private static Dictionary<int,string> InitializeDictionary()
        {
            Dictionary<int, string> drinksOrder = new Dictionary<int, string>()
            {
                { 100, "Lemonade"},
                { 203, "Gin and tonic" },
                { 145, "Small white wine"},
                { 701, "Coke" },
                { 361, "Orange juice" }
            };

            Console.WriteLine("Drinks order created - Dictionary initialized.");

            return drinksOrder;
        }

        private static void CheckDrinks(Dictionary<int, string> barOrder)
        {
            Console.WriteLine("\n\nCheck if certain drinks exist in the order, using the drinks name....\n");

            //someone wants to know if their Coke is in the order, so we need to check
            if (barOrder.ContainsValue("Coke"))
            {
                Console.WriteLine("There's a Coke in the order.");
            }
            else
            {
                Console.WriteLine("There's no Coke in the order.");
            }

            if (barOrder.ContainsValue("Wine"))
            {
                Console.WriteLine("There's a Wine in the order.");
            }
            else
            {
                Console.WriteLine("There's no Wine in the order.");
            }

            
            Console.WriteLine("\n\nNow check if a certain drink is in the order...");

            string selectedDrink = "No drink found";

            //check drink reference
            if (barOrder.ContainsKey(361))
            {
                selectedDrink = barOrder[361];
            }

            Console.WriteLine("Get Drink using key > " + selectedDrink);
            Console.WriteLine("\n");

        }

        private static void WriteDictionary(Dictionary<int, string> list)
        {
            Console.WriteLine("\n****** BAR ORDER ******");

            foreach (var item in list)
            {
                Console.WriteLine(item.Key + ": " + item.Value);
            }

            if (list.Count == 0)
            {
                Console.WriteLine("---This order is empty---");
            }

            Console.WriteLine("--------------------------\n");
            WaitForKeyPress();
        }

        private static void AddDrinks(Dictionary<int,string> bardrinks)
        {
            Console.WriteLine("Add two drinks to the order.....");

            bardrinks.Add(487, "Sparkling water");
            bardrinks.Add(925, "Prosecco");
        }

    }
}


Summary

Now you know how to get or add a C# keyvalue pair, initialize a Dictionary, convert it to JSON, you can see how useful they are.

You may also be interested in: