Skip to content

Instantly share code, notes, and snippets.

@ctrlShiftBryan
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save ctrlShiftBryan/c89e7c0835f6a6c24e33 to your computer and use it in GitHub Desktop.

Select an option

Save ctrlShiftBryan/c89e7c0835f6a6c24e33 to your computer and use it in GitHub Desktop.
//a class that has a parent id and contains a list of children
public class Folder {
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public List<Folder> Children { get; set; }
public int Level { get; set; }
}
//a utility class to nest a list
public static class FolderListNest{
public static List<Folder> NestList(this List<Folder> list){
//find roots
var nestedList = new List<Folder>();
var roots = list.Where(x => x.ParentId == null);
//set children for each root
foreach(var root in roots){
SetChildren(root, list, 0);
root.Children = list.Where(x => x.ParentId == root.Id).ToList();
nestedList.Add(root);
}
return nestedList;
}
private static void SetChildren(Folder root, List<Folder> list, int level){
//if this has any children
var allChild = list.Where(x => x.ParentId == root.Id).ToList();
if (allChild.Any())
{
level = level + 1;
//check if each child also has children
foreach (var c in allChild)
{
c.Level = level;
SetChildren(c, list, level); //recurse!
}
root.Children = allChild;
}
}
}
void Main()
{
//setup some test data
var list = new List<Folder>();
list.Add(new Folder{ Id = 1, Name = "A 1", ParentId = null });
list.Add(new Folder{ Id = 2, Name = "B 1", ParentId = 1 });
list.Add(new Folder{ Id = 3, Name = "B 2", ParentId = 1 });
list.Add(new Folder{ Id = 4, Name = "C 1", ParentId = 2 });
list.Add(new Folder{ Id = 5, Name = "C 2", ParentId = 2 });
list.Add(new Folder{ Id = 6, Name = "D 1", ParentId = 3 });
list.Add(new Folder{ Id = 7, Name = "D 2", ParentId = 3 });
list.Add(new Folder{ Id = 8, Name = "E 1", ParentId = null });
list.Add(new Folder{ Id = 9, Name = "F 1", ParentId = 8 });
list.Add(new Folder{ Id = 10, Name = "G 1", ParentId = 9 });
list.Add(new Folder{ Id = 11, Name = "H 1", ParentId = 10 });
list.NestList().Dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment