Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Converting flat structure to hierarchical

Tags:

c#

linq

What is the easiest and somewhat efficient way to convert a flat structure:

object[][] rawData = new object[][] 
{ 
  { "A1", "B1", "C1" }, 
  { "A1", "B1", "C2" },
  { "A2", "B2", "C3" }, 
  { "A2", "B2", "C4" }
  // .. more 
};

into a hierarchical structure:

class X
{
  public X () 
  {
    Cs = new List<string>();
  }
  public string A { get; set; }
  public string B { get; set; }
  public List<string> Cs { get; private set; }
}

the result should look like this

// pseudo code which describes structure:
result =
{
  new X() { A = "A1", B = "B1", Cs = { "C1", "C2" } },
  new X() { A = "A2", B = "B2", Cs = { "C3", "C4" } }
}

Preferably using Linq extension methods. Target class X could be changed (eg. a public setter for the List), only if not possible / useful as it is now.

like image 226
Stefan Steinegger Avatar asked Jun 18 '10 13:06

Stefan Steinegger


1 Answers

for this particular case:

   .GroupBy( x => new { a = x[0], b = x[1] } )
   .Select( x => new { A = x.Key.a, B = x.Key.b, C = x.Select( c => c[2] ) })
like image 184
Andrey Avatar answered Oct 06 '22 18:10

Andrey