I have a variable of type Dictionary<MyType, List<MyOtherType>>
I want to convert it to a Lookup<MyType, MyOtherType>
.
I wanted to use Lambda functions to first, flatten the dictionary and then convert this to Lookup using the ToLookup()
. I got stuck with the dictionary. I thought about using SelectMany but can't get it working. Anyone has got an idea how to do it?
How about:
var lookup = dictionary.SelectMany(pair => pair.Value,
(pair, Value) => new { pair.Key, Value })
.ToLookup(pair => pair.Key, pair => pair.Value);
It does feel like a little bit of a waste doing this when the dictionary already has all the information grouped appropriately, but I can't see a simple way round that. Of course you could implement ILookup<TKey, TValue>
yourself with a wrapper around the dictionary...