Upendra Chaudhari
Upendra Chaudhari

Reputation: 6543

how to get key from value in hash table

I have hashtable with key and values and in my code I am iterating hashtable through values like below :

foreach (Object clientObject in ClientList.Values)
{
    // code to perform operation based on value
    ......
}

Where ClientList is hashtable. Now I want to get key of perticualar value from hashtable in my code. is there any way to achieve that ?

Thanks

Upvotes: 5

Views: 12431

Answers (3)

xanatos
xanatos

Reputation: 111940

If you want the list of keys that have a certain value, using LINQ (.NET >= 3.5)

object searchedValue = something;

IEnumerable<object> keys = ClientList.Cast<DictionaryEntry>().Where(p => ClientList.Values == searchedValue).Select(p => p.Key);

This probably isn't what you wanted, but it's what you asked.

(the code means: take all the elements of ClientList (each element is a "tuple" of key and value) and search the one(s) that has the value equal to the searched value. Take the keys of those elements.

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176956

Its not possible to get the Key by using the value.

One of the reason is key are unique and Value are not unique in the HashTable.

You can use @Fischermaen way to read the value.

Upvotes: 1

Fischermaen
Fischermaen

Reputation: 12468

You have to iterate through the table in this way:

        Hashtable clientList = new Hashtable();

        foreach (DictionaryEntry dictionaryEntry in clientList)
        {
            // work with value.
            Debug.Print(dictionaryEntry.Value.ToString());

            // work with key.
            Debug.Print(dictionaryEntry.Key.ToString());
        }

Upvotes: 5

Related Questions