Get Dictionary Key by Value in C#
-
Get Dictionary Key by Value With the
foreach
Loop in C - Get Dictionary Key by Value With the Linq Method in C
This tutorial will introduce methods to get a dictionary key with value in C#.
Get Dictionary Key by Value With the foreach
Loop in C
Unfortunately, there is no built-in method for getting the key by value from a dictionary in C#. We have to rely on some user-defined approaches to achieve this goal. The foreach
loop is used to iterate through a data structure. We can use the foreach
loop with an if
statement to get the key by value from a dictionary in C#. The following code example shows us how to get a dictionary key by value with the foreach
loop in C#.
using System;
using System.Collections.Generic;
using System.Linq;
namespace get_dictionary_key_by_value
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> types = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
string key = "";
foreach(var pair in types)
{
if(pair.Value == "one")
{
key = pair.Key;
}
}
Console.WriteLine(key);
}
}
}
Output:
1
We created the dictionary types
and iterated through types
with a foreach
loop to find the key associated with the value one
. We used the foreach
loop to iterate through each pair in the types
dictionary and checked whether each pair’s value matches one
. If a pair value pair.value
matches one
, we store the key of the pair inside the key
string using key = pair.key
.
Get Dictionary Key by Value With the Linq Method in C
The Linq or language integrated query is used to integrate the functionality of SQL queries in C#. We can use Linq to get the dictionary key by dictionary value. See the following code example.
using System;
using System.Collections.Generic;
using System.Linq;
namespace get_dictionary_key_by_value
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> types = new Dictionary<string, string>()
{
{"1", "one"},
{"2", "two"},
{"3", "three"}
};
var myKey = types.FirstOrDefault(x => x.Value == "one").Key;
Console.WriteLine(myKey);
}
}
}
Output:
1
We created the dictionary types
and saved the key associated with the value one
inside the myKey
string using Linq in C#.