5

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
2
  • You can do that with a dictionary. See more here: stackoverflow.com/questions/255341/… Commented Aug 29, 2012 at 12:13
  • 1
    This completely defeats the purpose of the Hashtable. Why would you do that? BTW: Since .NET 2.0 you should be using Dictionary<TKey, TValue> instead. Commented Aug 29, 2012 at 12:13

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Dictionary is better
3

If you looking for O(1) solution, then you may need to implement the reversed Hashtable as well where the value of this table will be key and key becomes corresponding value.

Comments

2

You can use Linq operators

x.Keys.OfType<String>().FirstOrDefault(a => x[a] == "20")

You can iterate with foreach

Comments

1

I strongly recommend to use two Dictionary<string, string> but this would mean that their is a 1-1 relationship between the items:

var dict1 = new Dictionary<string, string>();
var dict2 = new Dictionary<string, string>();

dict1.Add("1", "10");
dict2.Add("10", "1");

dict1.Add("2", "20");
dict2.Add("20", "2");

dict1.Add("3", "30");
dict2.Add("30", "3");

var valueOfDictOne = dict1["1"];
var valueOfDictTwo = dict2["10"];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.