17

I have a Dictionary that has a signature: Dictionary<int, List<string>>. I'd like to convert it to a Lookup with a signature: Lookup<int, string>.

I tried:

Lookup<int, string> loginGroups = mapADToRole.ToLookup(ad => ad.Value, ad => ad.Key);

But that is not working so well.

dotnetN00b
  • 5,021
  • 13
  • 62
  • 95

1 Answers1

34

You could use:

var lookup = dictionary.SelectMany(p => p.Value
                                         .Select(x => new { p.Key, Value = x}))
                       .ToLookup(pair => pair.Key, pair => pair.Value);

(You could use KeyValuePair instead of an anonymous type - I mostly didn't for formatting reasons.)

It's pretty ugly, but it would work. Can you replace whatever code created the dictionary to start with though? That would probably be cleaner.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I think you mean: `Select(x => new { Key = p.Key, Value = x})` – Saeed Amiri May 02 '12 at 19:25
  • 1
    @SaeedAmiri: No, I meant what I wrote. It should work just fine as it is - the `Key` property name is inferred. – Jon Skeet May 02 '12 at 19:27
  • Nice I never tried it :) – Saeed Amiri May 02 '12 at 19:28
  • You're missing a `)` in your code :) – dotnetN00b May 02 '12 at 19:32
  • @JonSkeet: Out of curiosity, why do you need the Value = x? Shouldn't that be ascertained automatically? – dotnetN00b May 02 '12 at 19:38
  • @dotnetN00b: Well, I *could* have just used `x`, and then used `pair.x` in the `ToLookup` call - but that was ugly. I *could* have named the lambda expression parameter `Value`, but that would have been confusing with the previous `pair.Value`. Hence the `x = Value` compromise. I tried a few alternatives :) – Jon Skeet May 02 '12 at 19:46
  • @JonSkeet: You said to "replace whatever code created the dictionary" - how to? I can't use yield return in combination with ILookup. I receive multiple Key->List (i.e. IGrouping) in a loop, how to write a nice function which returns ILookup? – D.R. Nov 29 '13 at 17:42
  • @D.R.: I have no idea what the context is here. You're answering a question from a year and a half ago, and we don't know anything about your situation. I suspect you should ask a new question. – Jon Skeet Nov 29 '13 at 17:45
  • http://stackoverflow.com/questions/20291147/how-to-return-ilookup-directly-without-using-a-dictionary-ilookup-converter – D.R. Nov 29 '13 at 17:52