问题
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