Skip to content

Instantly share code, notes, and snippets.

@jonathascosta
Created February 20, 2014 17:52
Show Gist options
  • Save jonathascosta/9119503 to your computer and use it in GitHub Desktop.
Save jonathascosta/9119503 to your computer and use it in GitHub Desktop.
Transforms a flat list into a hierarchic collection
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;
}
}
@M33Media
Copy link

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?

public class Category 
{
public Int32 Id { get; set; }
public Int32 ParentId { get; set; }
public string Text { get; set; }
public IEnumerable<Category> Nodes { get; set; } = new List<Category>();
}
model.Categories.AsHierarchy(x => x.Parent, x => x.Nodes);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment