Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key by value in hash table c# [duplicate]

Tags:

c#

hashtable

I want to get the key of my value but this does not Possible in Hashtable
Is there data stretcher to do this ??

    Hashtable x = new Hashtable();
    x.Add("1", "10");
    x.Add("2", "20");
    x.Add("3", "30");

    x.GetKey(20);//equal 2
like image 819
motaz99 Avatar asked Aug 29 '12 12:08

motaz99


1 Answers

If all your keys are strings.

var key = x.Keys.OfType<String>().FirstOrDefault(s => x[s] == "20")

or better use a Dictionary instead:

Dictionary<string, string> x = new Dictionary<string, string>();
x.Add("1", "10");
x.Add("2", "20");
x.Add("3", "30");

string result = x.Keys.FirstOrDefault(s => x[s] == "20");

If you know that your value will always have just one distinct key, use Single instead of FirstOrDefault.

like image 190
sloth Avatar answered Sep 28 '22 18:09

sloth