Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Convert Dictionary to Lookup

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?


2 Answers

Same as Jon's method, but avoiding the creation of an anonymous type:

var lookup = dictionary
            .SelectMany(p => p.Value, Tuple.Create)
            .ToLookup(p => p.Item1.Key, p => p.Item2);
like image 193
3dGrabber Avatar answered Sep 14 '25 21:09

3dGrabber


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...

like image 28
Jon Skeet Avatar answered Sep 14 '25 21:09

Jon Skeet