简体   繁体   中英

C# LINQ - convert nested dictionary to a list

How do I flatten a nested dictionary into a list of some objects ( SomeObject in the following example) which should hold keys of those dictionaries?

For example: let's have a dictionary of the following type

var nestedDictionary = new Dictionary<int, Dictionary<int, string>>();

then, let's have this class

public class SomeObject
{
   public int var1;
   public int var2;
   public string someStringVar;
}

How do I convert nestedDictionary to a List<SomeObject> where var1 is the key of the outer dictionary, var2 is the key of the inner dictionary and someStringVar is the string value of the inner dictionary?

Essentially, how do I transfer this:

nestedDict[0][0] = "foo";
nestedDict[0][1] = "bar";
nestedDict[0][2] = "foo1";
nestedDict[1][0] = "bar1";
nestedDict[1][1] = "foo2";
nestedDict[1][2] = "bar2";

to this (in pseudo C# just to visualize it)

objList[0] = SomeObject { var1 = 0, var2 = 0, someStringVar = "foo" }
objList[1] = SomeObject { var1 = 0, var2 = 1, someStringVar = "bar" }
objList[2] = SomeObject { var1 = 0, var2 = 2, someStringVar = "foo1" }
objList[3] = SomeObject { var1 = 1, var2 = 0, someStringVar = "bar1" }
objList[4] = SomeObject { var1 = 1, var2 = 1, someStringVar = "foo2" }
objList[5] = SomeObject { var1 = 1, var2 = 2, someStringVar = "bar2" }

using LINQ?

You can use SelectMany() and write something like:

var objList = nestedDictionary.SelectMany(
    pair => pair.Value.Select(
        innerPair => new SomeObject() {
            var1 = pair.Key,
            var2 = innerPair.Key,
            someStringVar = innerPair.Value
        })).ToList();

This should work:

var flattened =
from kvpOuter in nestedDictionary
from kvpInner in kvpOuter.Value
select new SomeObject()
{
    var1 = kvpOuter.Key,
    var2 = kvpInner.Key,
    someStringVar = kvpInner.Value
};
var list = flattened.ToList(); // if you need a list...

This will give you an enumerable of IEnumerable<SomeObject> :

var results = from d in nestedDictionary
              from innerD in d.Value
              select new SomeObject { var1 = d.Key, var2 = innerD .Key, someStringVar = innerD .Value };

Call results.ToList or results.ToArray to get either a List<SomeObject> or SomeObject[] respectively.

var xxx = nestedDictionary.SelectMany(
                    kvp =>
                    kvp.Value.Select(
                        xx => new SomeObject() {var1 = kvp.Key, var2 = xx.Key, someStringVar = xx.Value}));

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