Created
February 20, 2014 17:52
-
-
Save jonathascosta/9119503 to your computer and use it in GitHub Desktop.
Transforms a flat list into a hierarchic collection
This file contains 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 LinqExtensions | |
{ | |
public static IEnumerable<T> AsHierarchy<T>(this IEnumerable<T> collection, | |
Func<T, T> parentSelector, Expression<Func<T, IEnumerable<T>>> childrenSelector, T root = default(T)) | |
{ | |
var items = collection.Where(x => parentSelector(x).Equals(root)).Safe(); | |
foreach (var item in items) | |
{ | |
var childrenProperty = (childrenSelector.Body as MemberExpression).Member as PropertyInfo; | |
childrenProperty.SetValue(item, collection.AsHierarchy(parentSelector, childrenSelector, item), null); | |
} | |
return items; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi.This snippet seems very interresting for me, but how to invoke it?
I dont understand the x=>x.Parent? Can you give an example to point me in the right direction?