user350233
user350233

Reputation: 139

Find from a hashtable using the value

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 above hashtable that has a value of 20 using LinQ

Upvotes: 2

Views: 4919

Answers (2)

Richard
Richard

Reputation: 108975

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.

Upvotes: 4

Mark Byers
Mark Byers

Reputation: 837916

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

Upvotes: 4

Related Questions