LINQ Convert Dictionary to Lookup

◇◆丶佛笑我妖孽 提交于 2019-12-18 03:55:00

问题


I have a variable of type Dictionary<MyType, List<MyOtherType>>
I want to convert it to a Lookup<MyType, MyOtehrType>.

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?


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/1464200/linq-convert-dictionary-to-lookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!