How to Get Dictionary Value by Key in C#

Muhammad Maisam Abbas Feb 02, 2024
  1. Get Dictionary Value by Key With [] Method in C#
  2. Get Dictionary Value by Key With TryGetKey() Function in C#
  3. Get Dictionary Value by Key With the FirstOrDefault() Method in C#
How to Get Dictionary Value by Key in C#

In this tutorial, we will discuss how to get the value of a dictionary by the key in C#.

Get Dictionary Value by Key With [] Method in C#

The Dictionary<T1,T2> class can be used to declare a dictionary in C#. A dictionary is a data structure that holds data in the form of key-value pairs. We can get the value in the dictionary by using the key with the [] method in C#.

The [] operator plays a pivotal role in swiftly accessing values within a dictionary using their keys. By using the [] operator directly after the dictionary instance and providing the desired key within the square brackets, you can effortlessly retrieve the value associated with that key.

To demonstrate this concept, consider the following example:

using System;
using System.Collections.Generic;

namespace get_dictionary_value {
  class Program {
    static void Main(string[] args) {
      Dictionary<string, string> mydictionary = new Dictionary<string, string>();

      mydictionary.Add("Key 1", "Value 1");
      mydictionary.Add("Key 2", "Value 2");
      mydictionary.Add("Key 3", "Value 3");

      Console.WriteLine(mydictionary["Key 3"]);
    }
  }
}

Output:

Value 3

We created a dictionary, mydictionary, with the Dictionary<string, string> class. After that, we retrieved the value of the Key 3 key in mydictionary with the [] method. The only flaw with this method is that it raises an exception if the key is not found in the dictionary.

Get Dictionary Value by Key With TryGetKey() Function in C#

The TryGetKey() function checks whether a key exists in a dictionary or not in C#. It returns a boolean value.

If the key exists in the dictionary, the function returns true and changes the value of the out parameter to the value of the key in the dictionary. If the key does not exist in the dictionary, the function returns false.

The TryGetKey() function handles the exception raised in the [] method if the key is not present in the dictionary.

Method Signature and Behavior

The TryGetValue() method carries the following signature:

bool TryGetValue(TKey key, out TValue value)
  • TKey is the type of the key you are searching for.
  • TValue is the type of the value associated with the key.

When you invoke the TryGetValue() method, the following scenarios unfold:

  • If the key exists in the dictionary, the method returns true. It assigns the value associated with the key to the out parameter, value.
  • If the key is not present in the dictionary, the method returns false. The value parameter remains unassigned.

The following code example shows us how to get the value in a dictionary by key with the TryGetkey() function in C#.

using System;
using System.Collections.Generic;

namespace get_dictionary_value {
  class Program {
    static void Main(string[] args) {
      Dictionary<string, string> mydictionary = new Dictionary<string, string>();

      mydictionary.Add("Key 1", "Value 1");
      mydictionary.Add("Key 2", "Value 2");
      mydictionary.Add("Key 3", "Value 3");

      string value;
      bool hasValue = mydictionary.TryGetValue("Key 3", out value);
      if (hasValue) {
        Console.WriteLine(value);
      } else {
        Console.WriteLine("Key not present");
      }
    }
  }
}

Output:

Value 3

In this example, the TryGetValue() method is utilized to ascertain the presence of the key Key 3 in the myDictionary dictionary. If the key is found, the associated value Value 3 is retrieved and printed to the console. If the key is not present, the message Key not present is displayed.

Get Dictionary Value by Key With the FirstOrDefault() Method in C#

The FirstOrDefault() method is part of the LINQ (Language Integrated Query) library in C#. It is primarily used to query collections and sequences, aiming to return the first element that satisfies a given condition.

This method proves useful when you need to find a specific element in a collection based on a certain criterion.

The Power of FirstOrDefault() with Dictionaries

Although the FirstOrDefault() method is often associated with querying collections, it can also be employed to retrieve values from dictionaries.

This is especially handy when you want to fetch a dictionary value by key while handling the scenario where the key might not exist.

The method’s behavior aligns well with dictionary access requirements, making it a valuable tool in your C# programming toolkit.

Method Signature and Behavior

The FirstOrDefault() method offers the following signature:

TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
  • TSource represents the type of the elements in the source collection.
  • source is the source collection from which to retrieve elements.
  • predicate is a condition that determines the elements to be considered for selection.

When applied to dictionaries, the FirstOrDefault() method considers each key-value pair in the dictionary as a sequence of elements, allowing you to find the desired value based on a specified key.

Example: Using FirstOrDefault() to Retrieve Dictionary Values

Let’s dive into a practical example to illustrate how the FirstOrDefault() method can be used to retrieve dictionary values based on keys:

using System;
using System.Collections.Generic;
using System.Linq;

namespace DictionaryValueByKey {
  class Program {
    static void Main(string[] args) {
      // Create a dictionary and populate it with key-value pairs
      Dictionary<string, string> myDictionary = new Dictionary<string, string> {
        { "Key 1", "Value 1" }, { "Key 2", "Value 2" }, { "Key 3", "Value 3" }
      };

      // Specify the key to retrieve the value for
      string targetKey = "Key 2";

      // Use FirstOrDefault() to retrieve the value based on the key
      string targetValue = myDictionary.FirstOrDefault(pair => pair.Key == targetKey).Value;

      // Print the retrieved value or a message if the key is not found
      if (targetValue != null) {
        Console.WriteLine(targetValue);
      } else {
        Console.WriteLine("Key not found");
      }
    }
  }
}

Output:

Value 2

In this example, the FirstOrDefault() method is utilized to retrieve the value associated with the target key Key 2 from the myDictionary dictionary. If the key is found, the associated value Value 2 is printed to the console. If the key is not present, the message Key not found is displayed.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp Dictionary