How to convert the nested hierarchical object to flatten objects by using LINQ? I know that we can easily use foreach loop to achieve that. But I’m wondering if there is a way to write it in LINQ.
class Person{
public int ID {get;set}
public string Name {get;set}
public List<Person> Children {get;}
}
Data :
ID : 1
Name : Jack
Children
2 | Rose
3 | Paul
I like to convert this data into flatten format like below.
1 | Jack
2 | Rose
3 | Paul
How can we do it with Linq?
If you want it to flatten an arbitrarily deep tree of people, I suggest the following:
There isn’t really any good way to shorten this with LINQ, because anonymous lambdas can’t call themselves recursively without implementing Y. You could “reduce” the above method to
or alternatively
but that seems sort of unnecessary to me.