2

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

user350233
  • 139
  • 1
  • 5
  • 9

2 Answers2

4

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.

Richard
  • 106,783
  • 21
  • 203
  • 265
4

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);
Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452