Skip to content

Instantly share code, notes, and snippets.

@lukencode
Last active October 13, 2015 17:17
Show Gist options
  • Save lukencode/4229296 to your computer and use it in GitHub Desktop.
Save lukencode/4229296 to your computer and use it in GitHub Desktop.
I have know idea if this will work...
public static class Hierarchyize
{
public static List<Nested<T>> Transform<T>(IEnumerable<T> items, Func<T, T, bool> isParentFunction, Func<T, bool> isRootFunction)
{
Action<Nested<T>> setChildren = null;
setChildren = parent =>
{
parent.Children = items
.Where(childItem => isParentFunction(childItem, parent.Item))
.Select(childItem => new Nested<T> { Item = childItem })
.ToList();
//Recursively call the SetChildren method for each child.
parent.Children
.ForEach(setChildren);
};
//Initialize the hierarchical list to root level items
List<Nested<T>> hierarchicalItems = items
.Where(rootItem => isRootFunction(rootItem))
.Select(childItem => new Nested<T> { Item = childItem })
.ToList();
//Call the SetChildren method to set the children on each root level item.
hierarchicalItems.ForEach(setChildren);
return hierarchicalItems;
}
}
public class Nested<T>
{
public T Item { get; set; }
public List<Nested<T>> Children { get; set; }
public Nested()
{
Children = new List<Nested<T>>();
}
}
var nestedList = Hierarchyize.Transform(flatList,
(c, p) => c.ParentID == p.ID, //is parent
(c) => c.ParentID == 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment