Search code examples
c#linqflatten

c# Flatten multi-layer of list to dictionary and generate key by each element's layers info


I have a structure like this

List<X> tableX;

class X
{
    List<Y> tableY;
}

class Y
{
    string Name;
    int data;
}

Are there a method to flatten it to a dictionary, which I can input the table name and index to get Y like this

var dict = tableX
  .SelectMany(x => x.tableY)
  .ToDictionary(y => $"tableX[{index of x}].tableY[{index of y}]");

Y Yij = dict["tableX[i].tableY[j]"]

Solution

  • In SelectMany you could return a tuple containing the index of X, the index of Y within that X and Y itself.

    You can then project that into a dictionary using your desired key:

    var dict = tableX
        .SelectMany((x, xi) => x.tableY.Select((y, yi) => (xi, yi, y)))
        .ToDictionary(
            tuple => $"tableX[{tuple.xi}].tableY[{tuple.yi}]",
            tuple => tuple.y);