0

hi all,
i have started recently learning c# and when i do some code using the hashtable, i could n't get the value of a particular key
we can get a value for a particular key but do we can do the verse ?

3
Contributors
3
Replies
18
Views
2 Years
Discussion Span
Last Post by Lucaci Andrew
1

Loop the entries:

Hashtable hashtable = new Hashtable();

hashtable.Add("1", "one");
hashtable.Add("2", "TEST");
hashtable.Add("3", "one");

string key = string.Empty;
foreach (DictionaryEntry entry in hashtable)
{
    if ((string)entry.Value == "TEST")
    {
        key = (string)entry.Key;
        break;
    }
}

Console.WriteLine(key);

Edited by pritaeas

0

You could also use LINQ to search for that. Knowing that Hashtable uses internally DictionarEntry to store its items (since .Net 1.1), we can cast it to such and search for the item we want.

var hash = new Hashtable();

hash.Add("1", "one");
hash.Add("2", "TEST");
hash.Add("3", "one");

var res = hash.Cast<DictionaryEntry>()
              .First(i => i.Value as string == "TEST")
              .Key as string;

If you have the same value multiple times in your hashtable, you could get all keys witht that value by using this:

var hash = new Hashtable();

hash.Add("1", "one");
hash.Add("2", "TEST");
hash.Add("3", "one");
hash.Add("4", "TEST");

var res = hash.Cast<DictionaryEntry>()
              .Where(i => i.Value as string == "TEST")
              .Select(i => i.Key as string);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.