Linq: Converting flat structure to hierarchical
Posted
by Stefan Steinegger
on Stack Overflow
See other posts from Stack Overflow
or by Stefan Steinegger
Published on 2010-06-18T13:51:02Z
Indexed on
2010/06/18
14:13 UTC
Read the original article
Hit count: 1423
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.
© Stack Overflow or respective owner