Reputation: 2293
I've a dictionary member of type Dictionary<string, Dictionary<string, List<SomeType>>>
. What I want is to get nested dictionary from this i.e. Dictionary<string, List<SomeType>>
. I thought I'd get this using myDict.Values
, but that's actually returning ValueCollection
and not the nested-dictionary itself.
Now I'm trying to get this done using ValueCollection.ToDictionary function, but please share if you've already done something similar.
Update I want to return nested-dictionary
Dictionary<string, List<SomeType>> GetKeyPairValues()
{
// get nested dictionary from this.myDict
}
Upvotes: 0
Views: 3601
Reputation: 75306
You need to use GroupBy
to group by Key
then merge all list with the same key:
Dictionary<string, List<SomeType>> GetKeyPairValues()
{
return dic.Values.SelectMany(d => d)
.GroupBy(p => p.Key)
.ToDictionary(g => g.Key,
g => g.SelectMany(pair => pair.Value)
.ToList());
}
Upvotes: 2
Reputation: 82096
What I want is to get nested dictionary
return myDict.Values.ToDictionary(x => x.Keys, x => x.Values);
Based on your comment, and looking at how complex the LINQ expression is going to have to be for this, why not just go for a basic for loop e.g.
Dictionary<string, List<SomeType>> GetKeyPairValues()
{
foreach (var pair in dict)
{
yield return pair.Value;
}
}
It also might be more efficient than using LINQ.
Upvotes: 2
Reputation: 11964
Try this:
var dictionary = new Dictionary<string, Dictionary<string, List<int>>>();//initialize your source dictionary
var mergedDictionary = dictionary.SelectMany(d => d.Value).ToDictionary(k=>k.Key, k=>k.Value);
Update: use ToDictionary
Upvotes: 1
Reputation: 2335
Actually Dictionary<>
implements multiple Values
properties. If you use it through IDictionary<>
you get a ICollection<TValue>
IDictionary<string, Dictionary<string, List<SomeType>>> dict = new Dictionary<string, Dictionary<string, List<SomeType>>>();
ICollection<Dictionary<string, List<SomeType>>> = dict.Values;
Upvotes: 0