44

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
  • 11,529
  • 10
  • 59
  • 109

2 Answers2

58

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
  • 31,518
  • 9
  • 83
  • 102
  • 9
    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
  • 1
    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
11

One fast way:

var myKeys = myLookup.Select(l=>l.Key);
KeithS
  • 65,745
  • 16
  • 102
  • 161