Share via


dictionary get key by value

Question

Thursday, May 26, 2011 4:53 AM

Hello

            I have a dictionary <int , string > dic = new dictionary <int , string >();

 

i have a value i want to get it key please advice

It's Me

All replies (6)

Thursday, May 26, 2011 11:13 AM ✅Answered | 1 vote

If using Linq...

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "Jack");
dict.Add(2, "Peter");
dict.Add(3, "Chris");
dict.Add(4, "Peter");

var keys = from entry in dict 
      where entry.Value == "Peter" 
      select entry.Key;

foreach (var key in keys) 
  Console.WriteLine(key);

//should output the following:
// 2
// 4

Thursday, May 26, 2011 12:37 PM ✅Answered


Thursday, May 26, 2011 5:08 AM

You can get both key and value.

 

    Dictionary<int, string> dic = new Dictionary<int, string>();
    dic.Add(1, "apple");

    foreach (KeyValuePair<int, string> pair in dic)
    {
      Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
    }

Thursday, May 26, 2011 5:15 AM

hello

         thanks for reply 

 

i am looping on values 

 

 foreach (string s in dic.Values)

{

  // here i have a value i want to get the "key" from value

}

It's Me


Thursday, May 26, 2011 5:27 AM

You might use below foreach loop and use and if condition.

 

    Dictionary<int, string> dic = new Dictionary<int, string>();
    dic.Add(1, "apple");

    foreach (KeyValuePair<int, string> pair in dic)
    {
      if (pair.Value == "apple")
      {
        Console.WriteLine("{0}", pair.Key);
      }
    }

Monday, October 27, 2014 11:21 PM

Hello.

Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "apple");
dic.Add(2, "orange");
int myValue = dic.FirstOrDefault(x => x.Value == "orange").Key;