Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a value from a hashtable

If I were having a Generic list I would have done some thing like this

myListOfObject.FindAll(x=>(x.IsRequired==false));

What if I need to do similar stuff in Hashtable? Copying to temporary hashtable and looping and comparing would be that last thing I would try :-(

like image 781
Shanadas Avatar asked Jul 02 '12 12:07

Shanadas


People also ask

How do I find the value of a Hashtable?

util. Hashtable. get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key.

How do you check if a Hashtable contains a key?

Hashtable containsKey() Method in Java Hashtable. containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table.

Is Hashtable a key value pair?

Hashtable stores key/value pair in hash table. In Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

Is Hashtable value based collection?

The Hashtable is a non-generic collection that stores key-value pairs, similar to generic Dictionary<TKey, TValue> collection. It optimizes lookups by computing the hash code of each key and stores it in a different bucket internally and then matches the hash code of the specified key at the time of accessing values.


1 Answers

Firstly, use System.Collections.Generic.Dictionary<TKey, TValue> for better strong-type support as opposed to Hashtable.

If you need to just find one key or one value, use the methods ContainsKey(object key) or ContainsValue(object value), both of which are found on the Hashtable type.

Or you can go further and use linq extensions on the Hashtable parts:

Hashtable t = new Hashtable();
t.Add("Key", "Adam");

// Get the key/value entries.
var itemEntry = t.OfType<DictionaryEntry>().Where(de => (de.Value as string) == "Adam");

// Get just the values.
var items = t.Values.OfType<string>().Where(s => s == "Adam");

// Get just the keys.
var itemKey = t.Keys.OfType<string>().Where(k => k == "Key");
like image 98
Adam Houldsworth Avatar answered Oct 01 '22 15:10

Adam Houldsworth