I often end up working with systems where the data is delivered with some Id
property and possibly a parentId
prop, but never do anyone tempt to actually give me a nice recursive object to play with.
Now, the code below is merely a suggestion in how to solve these kind of "problems", I've created the FlatObject
to simulate an incoming with data.
class Program
{
static void Main(string[] args)
{
// Fill list with sample data
List<FlatObject> flatObjects = new List<FlatObject>
{
new FlatObject(1,0),
new FlatObject(2,0),
new FlatObject(3,0),
new FlatObject(4,0),
new FlatObject(5,1),
new FlatObject(6,2),
new FlatObject(7,6),
new FlatObject(8,6)
};
// call the recursive method
var recursiveObjects = FillRecursive(flatObjects, 0);
}
private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, int parentId)
{
List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
foreach (var item in flatObjects.Where(x => x.ParentId.Equals(parentId)))
{
recursiveObjects.Add(new RecursiveObject
{
Id = item.Id,
ParentId = item.ParentId,
Children = FillRecursive(flatObjects, item.Id)
});
}
return recursiveObjects;
}
}
public class FlatObject
{
public int Id { get; set; }
public int ParentId { get; set; }
public FlatObject(int id, int parentId)
{
Id = id;
ParentId = parentId;
}
}
public class RecursiveObject
{
public int Id { get; set; }
public int ParentId { get; set; }
public List<RecursiveObject> Children { get; set; }
}
I am aware of some Linq alternatives to solve the foreach
loop but that does hardly not change the approach of this.
private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, int parentId)
{
return flatObjects.Where(x => x.ParentId.Equals(parentId)).Select(item => new RecursiveObject
{
Id = item.Id, ParentId = item.ParentId, Children = FillRecursive(flatObjects, item.Id)
}).ToList();
}