56

How do I get the collection of keys from a Lookup<> I created through the .ToLookup() method?

I have a lookup which maps int-values to groups of instances of a custom class. I need a collection of all the int keys that the lookup contains. Any way to do this, or do I have to collect and save them separately?

magnattic
  • 12,638
  • 13
  • 62
  • 115

2 Answers2

72

You can iterate through the set of key-item groups and read off the keys, e.g.

var keys = myLookup.Select(g => g.Key).ToList();
Rup
  • 33,765
  • 9
  • 83
  • 112
  • 13
    Any theory as to why `Lookup` doesn't include `Keys` method unlike `Dictionary`? – NetMage Sep 14 '17 at 22:04
  • I don't know - best guess maybe because Lookup is provided by LINQ and you can use LINQ to extract the keys like this? Here are the current implementations from the .NET reference source: [Lookup](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,cb695d4a973ef608), [Dictionary](https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,d3599058f8d79be0). Their internal storage looks roughly the same. Dictionary has its own KeyCollection class, which would be easy enough to adapt for Lookup as well but isn't just compatible as-is. – Rup Sep 15 '17 at 19:11
  • 4
    Maybe it's relevant that, unlike dictionaries, the lookup doesn't enforce only a fixed set of keys. You can query on any key you like and you get a valid response. It may return an empty set, but it is still a valid response. – Tormod Aug 20 '20 at 08:59
15

One fast way:

var myKeys = myLookup.Select(l=>l.Key);
KeithS
  • 70,210
  • 21
  • 112
  • 164