简体   繁体   中英

How to convert ValueCollection to Dictionary?

I've a dictionary member of type Dictionary<string, Dictionary<string, List<SomeType>>> . What I want is to get nested dictionary from this ie 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
}

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 eg

Dictionary<string, List<SomeType>> GetKeyPairValues()
{
    foreach (var pair in dict)
    { 
        yield return pair.Value;
    }
}

It also might be more efficient than using LINQ.

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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM