locked
dictionary get key by value RRS feed

  • Question

  • 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
    Thursday, May 26, 2011 4:53 AM

Answers

  • 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
    

    • Marked as answer by It_s Meee Friday, May 27, 2011 12:31 PM
    Thursday, May 26, 2011 11:13 AM
  • ----
    • Marked as answer by It_s Meee Friday, May 27, 2011 12:31 PM
    • Edited by Link.fr Tuesday, November 11, 2014 11:21 AM
    Thursday, May 26, 2011 12:37 PM

All replies

  • 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:08 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:15 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);
          }
        }
    

    Thursday, May 26, 2011 5:27 AM
  • 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
    

    • Marked as answer by It_s Meee Friday, May 27, 2011 12:31 PM
    Thursday, May 26, 2011 11:13 AM
  • ----
    • Marked as answer by It_s Meee Friday, May 27, 2011 12:31 PM
    • Edited by Link.fr Tuesday, November 11, 2014 11:21 AM
    Thursday, May 26, 2011 12:37 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;
    

    Monday, October 27, 2014 11:21 PM