I have this model:
public class TreeModel
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
public static List<TreeModel> GetData()
{
var list = new List<TreeModel>()
{
new TreeModel() {Id = 1,ParentId = null,Name = "Name1"},
new TreeModel() {Id = 2,ParentId = null,Name = "Name2"},
new TreeModel() {Id = 3,ParentId = null,Name = "Name3"},
new TreeModel() {Id = 4,ParentId = 1,Name = "Name4"},
new TreeModel() {Id = 5,ParentId = 1,Name = "Name5"},
new TreeModel() {Id = 6,ParentId = 4,Name = "Name6"},
new TreeModel() {Id = 7,ParentId = 6,Name = "Name7"},
};
return list;
}
public static string ShowTree(List<TreeModel> source)
{
var text = "";
foreach (var item in source)
{
if (item.ParentId != null) continue;
text += item.Name + "\n";
var childs = source.Where(x => x.ParentId == item.Id).ToList();
if (!childs.Any()) continue;
{
foreach (var child in childs)
{
text += " " + child.Name + "\n"; //2 spaces
var childs2 = source.Where(x => x.ParentId == child.Id).ToList();
if (!childs2.Any()) continue;
{
foreach (var child2 in childs2)
{
text += " " + child2.Name + "\n"; //4 spaces
var childs3 = source.Where(x => x.ParentId == child2.Id).ToList();
if (!childs3.Any()) continue;
foreach (var child3 in childs3)
{
text += " " + child3.Name + "\n"; //6 spaces
}
}
}
}
}
}
return text;
}
}
with my method ShowTree
, I am able to get this:
Name1
Name4
Name6
Name7
Name5
Name2
Name3
Can someone help me transform this method in recursive one, in order to use it with a larger data-set.