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 ?

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);

thank you for great help,you solved my problem :)

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);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.