Get dictionary key by value in C#

Get dictionary key by value in C#

To get a dictionary key by its value in C#, you can use the LINQ extension methods First() or FirstOrDefault() to search for the first key-value pair in the dictionary where the value matches the given value. Here is an example:

 using System.Linq; // Create a dictionary Dictionary<int, string> dict = new Dictionary<int, string> { { 1, "apple" }, { 2, "banana" }, { 3, "orange" }, { 4, "pear" } }; // Get the key for a given value int key = dict.FirstOrDefault(x => x.Value == "orange").Key; // Output the key Console.WriteLine(key); // Output: 3 

In this example, we use FirstOrDefault() with a lambda expression to search for the first key-value pair where the value is equal to "orange". Then, we retrieve the key of that pair using the Key property. If no key-value pair is found where the value matches the given value, FirstOrDefault() will return the default value for the dictionary's key type (in this case, 0 for int), so you may want to check for that case separately.

Examples

  1. How to find dictionary key by value in C#?

    public static TKey GetKeyByValue<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TValue value) { foreach (KeyValuePair<TKey, TValue> pair in dictionary) { if (EqualityComparer<TValue>.Default.Equals(pair.Value, value)) { return pair.Key; } } throw new KeyNotFoundException("The specified value is not found in the dictionary."); } 

    Description: This code defines a method GetKeyByValue that searches for a value in a dictionary and returns its corresponding key. It iterates through each key-value pair in the dictionary and compares the values until a match is found.

  2. Get key from value in dictionary C#

    var key = dictionary.FirstOrDefault(x => x.Value.Equals(value)).Key; 

    Description: This code uses LINQ's FirstOrDefault method to find the first key in the dictionary where the value matches the specified value.


More Tags

language-lawyer dask activation laravel-4 global jakarta-ee rm icu http-status-code-415

More C# Questions

More Animal pregnancy Calculators

More Tax and Salary Calculators

More Mixtures and solutions Calculators

More Weather Calculators