Top 8 Ways to Get Value from Dictionary in c# | 2023

A dictionary in C# is a collection of key-value pairs, where each key is unique, and each key maps to a specific value. It provides an efficient way to store and retrieve data based on the key.

In this article, we will explore how to get value from dictionary in C# using various techniques.

1. Accessing Values using the Key

The primary way to get a value from a dictionary is by providing the corresponding key. The key acts as an index, allowing quick retrieval of the associated value. Let’s see a simple example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a dictionary with some data
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Accessing values using keys
        int johnsAge = ageDictionary["John"];
        int alicesAge = ageDictionary["Alice"];

        Console.WriteLine($"John's age: {johnsAge}");
        Console.WriteLine($"Alice's age: {alicesAge}");
    }
}

2. Using TryGetValue() method

It is important to note that accessing a value using the key directly, as shown in the above example, can throw a KeyNotFoundException if the key is not present in the dictionary. To avoid such exceptions, you can use the TryGetValue() method, which returns a boolean indicating whether the key was found and stores the value in an output variable.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using TryGetValue() method
        int bobsAge;
        if (ageDictionary.TryGetValue("Bob", out bobsAge))
        {
            Console.WriteLine($"Bob's age: {bobsAge}");
        }
        else
        {
            Console.WriteLine("Bob's age not found in the dictionary.");
        }

        // Trying to access a non-existent key
        int samsAge;
        if (ageDictionary.TryGetValue("Sam", out samsAge))
        {
            Console.WriteLine($"Sam's age: {samsAge}");
        }
        else
        {
            Console.WriteLine("Sam's age not found in the dictionary.");
        }
    }
}

3. Using ContainsKey() method

Before accessing a value using the key, you may want to check if the key exists in the dictionary to avoid exceptions. You can use the ContainsKey() method for this purpose:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using ContainsKey() method
        string searchName = "Alice";
        if (ageDictionary.ContainsKey(searchName))
        {
            int aliceAge = ageDictionary[searchName];
            Console.WriteLine($"Alice's age: {aliceAge}");
        }
        else
        {
            Console.WriteLine($"{searchName} not found in the dictionary.");
        }
    }
}

4. Using ElementAt() method (for OrderedDictionary)

If you are using an OrderedDictionary, which allows retrieval by index, you can use the ElementAt() method:

using System;
using System.Collections.Specialized;

class Program
{
    static void Main()
    {
        OrderedDictionary ageDictionary = new OrderedDictionary
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using ElementAt() method to get value by index
        int secondPersonAge = (int)ageDictionary.ElementAt(1).Value;
        Console.WriteLine($"Second person's age: {secondPersonAge}");
    }
}

5. Using LINQ

LINQ (Language Integrated Query) provides a powerful way to query collections, including dictionaries. You can use LINQ’s FirstOrDefault() method to get the first key-value pair that matches a specific condition.

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

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using LINQ to get value based on condition
        int ageOfBob = ageDictionary.FirstOrDefault(kv => kv.Key == "Bob").Value;
        Console.WriteLine($"Bob's age: {ageOfBob}");
    }
}

6. Using foreach loop

You can iterate through the dictionary using a foreach loop and access both the key and the value at each iteration.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using foreach loop to iterate through the dictionary
        foreach (var entry in ageDictionary)
        {
            string name = entry.Key;
            int age = entry.Value;
            Console.WriteLine($"{name}'s age: {age}");
        }
    }
}

7. Using the Values property

If you only need to access the values in the dictionary and not the keys, you can use the Values property. It returns a collection of all the values in the dictionary.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using the Values property to access all values
        ICollection<int> allAges = ageDictionary.Values;
        foreach (int age in allAges)
        {
            Console.WriteLine($"Age: {age}");
        }
    }
}

8. Using Deconstruction (C# 7.0 and later)

Starting from C# 7.0, you can use deconstruction to directly access the key and value of a dictionary entry within a foreach loop or assignment.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> ageDictionary = new Dictionary<string, int>
        {
            { "John", 30 },
            { "Alice", 25 },
            { "Bob", 28 }
        };

        // Using deconstruction to access key-value pairs
        foreach (var (name, age) in ageDictionary)
        {
            Console.WriteLine($"{name}'s age: {age}");
        }
    }
}

Conclusion

As you work with dictionaries, consider the specific needs of your application and choose the method that best suits your use case. Always prioritize efficiency, readability, and safety when accessing values from dictionaries to build robust and maintainable code. Happy coding!

Scroll to Top