从哈希表中找到一个值 [英] 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));
如果我需要在 Hashtable
中做类似的事情怎么办?复制到临时 hashtable
并进行循环和比较将是我最后尝试做的事情:-(
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 :-(
推荐答案
首先,使用 System.Collections.Generic.Dictionary< TKey,TValue>
获得更好的强类型支持,而不是哈希表
.
Firstly, use System.Collections.Generic.Dictionary<TKey, TValue>
for better strong-type support as opposed to Hashtable
.
如果您只需要查找一个键或一个值,请使用方法 ContainsKey(对象键)
或 ContainsValue(对象值)
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.
或者您可以走得更远,并在 Hashtable
部分上使用linq扩展:
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");
这篇关于从哈希表中找到一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!