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
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
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
.
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.
You can use Linq operators
x.Keys.OfType<String>().FirstOrDefault(a => x[a] == "20")
You can iterate with foreach
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"];