Last active
October 13, 2015 17:17
-
-
Save lukencode/4229296 to your computer and use it in GitHub Desktop.
I have know idea if this will work...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Nested<T> | |
{ | |
public T Item { get; set; } | |
public List<Nested<T>> Children { get; set; } | |
public Nested() | |
{ | |
Children = new List<Nested<T>>(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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