开发者

Find from a hashtable using the value

开发者 https://www.devze.com 2023-01-06 03:55 出处:网络
I have a following hash table: private Hashtable Sid2Pid = new Hashtable(); Sid2Pid.Add(1,10); Sid2Pid.Add(2,20);

I have a following hash table:

private Hashtable Sid2Pid = new Hashtable();

Sid2Pid.Add(1,10);
Sid2Pid.Add(2,20);
Sid2Pid.Add(3,20);
Sid2Pid.Add(4,30);

Now how to get the list of keys from the abov开发者_StackOverflowe hashtable that has a value of 20 using LinQ


Use a Dictionary<int, int> instead of a Hashtable (see here for why) then do the following:

var keys = Sid2Pid.Where(kvp => kvp.Value == 20)
                  .Select(kvp => kvp.Key);


A HashTable is IEnumerable of DictionaryEntry, with a little casting this can be converted into something the LINQ operators can work on:

var res = from kv in myHash.Cast<DictionaryEntry>
          where (int)kv.Value = targetValue
          select (int)kv.Key;

NB. This will throw an exception if you pass different types.

0

精彩评论

暂无评论...
验证码 换一张
取 消