I have a list of C# entities. My entity is defined as follows:
public class Item
{
// the id of an item
public Guid ID { get; set; }
// if this
Here's an alternative answer that builds a tree from the input and then traverses it in order. This traversal gives you sorted output.
class FlattenTree
{
// map each item to its children
ILookup- mapping;
public FlattenTree(IEnumerable
- list)
{
var itemLookup = list.ToDictionary(item => item.ID);
mapping = list.Where(i => i.ParentID.HasValue)
.ToLookup(i => itemLookup[i.ParentID.Value]);
}
IEnumerable
- YieldItemAndChildren(Item node)
{
yield return node;
foreach (var child in mapping[node].OrderBy(i => i.CreateDate))
foreach (var grandchild in YieldItemAndChildren(child))
yield return grandchild;
}
public IEnumerable
- Sort()
{
return from grouping in mapping
let item = grouping.Key
where item.ParentID == null
orderby item.CreateDate
from child in YieldItemAndChildren(item)
select child;
}
}
Invoke it like this:
var sorted = new FlattenTree(random).Sort();