从哈希表中查找值

Sha*_*das 4 .net c# collections hashtable

如果我有一个通用列表,我会做这样的事情

myListOfObject.FindAll(x=>(x.IsRequired==false));
Run Code Online (Sandbox Code Playgroud)

如果我需要做类似的事情Hashtable怎么办?复制到临时hashtable和循环和比较将是我会尝试的最后一件事:-(

Ada*_*rth 9

首先,使用System.Collections.Generic.Dictionary<TKey, TValue>更好的强类型支持而不是Hashtable.

如果您只需要找到一个键或一个值,请使用方法,ContainsKey(object key)或者ContainsValue(object value)Hashtable类型上找到这两个方法.

或者您可以进一步使用Hashtable部件上的linq扩展:

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");
Run Code Online (Sandbox Code Playgroud)