Find a value from a hashtable

最后都变了- 提交于 2021-02-07 18:19:16

问题


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 :-(


回答1:


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


来源:https://stackoverflow.com/questions/11293827/find-a-value-from-a-hashtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!