C# Dictionary

C# Code Snippets Dictionary
Share:

About

In this code snippet, we’ll take a look at dictionaries in C#.

Dictionaries can hold a collection of objects and are similar to lists. But unlike lists, the objects stored in the dictionary are paired with a key. That key can be used to access the object in the collection.

Now let’s look the code below to see how to use dictionaries.

Code:

using System;
using System.Collections.Generic;

namespace Dictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            //Dictionary<> uses a key - value pair unlike List<>
            //Dictionary<(key data type), (value data type)>
            Dictionary<string, string> myDictionary = new Dictionary<string, string>();

            //Add an item by first adding a key and than the value that will be referenced by the key.
            myDictionary.Add("One", "I am first.");
            myDictionary.Add("Two", "I am second.");
            myDictionary.Add("Three", "I am third.");

            //Show item in dictionary.
            showDictionaryItems(myDictionary);

            //Remove item by key.
            myDictionary.Remove("Two"); 

            //Show item in dictionary.
            showDictionaryItems(myDictionary);


            //Try to get the value by key. 
            string value = "";

            if (myDictionary.TryGetValue("One", out value))
            {
                Console.WriteLine(value);
            }

            //Check if the key exists.
            if (myDictionary.ContainsKey("One"))
            {
                Console.WriteLine("Key exists.");
            }
            else
            {
                Console.WriteLine("Key doesn't exist.");
            }

            //Clear the items.
            myDictionary.Clear();

            //Show item in dictionary.
            showDictionaryItems(myDictionary);

            Console.ReadLine();
        }

        public static void showDictionaryItems(Dictionary<string, string> myDictionary)
        {
            //Get the key and value of each item in the list.
            foreach (var item in myDictionary)
            {
                Console.WriteLine(item.Key + ": " + item.Value);
            }

            Console.WriteLine("");
        }
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger