I agree with Jeff that the simplest answer is to store the sorted data if this is your main access pattern. But let's say you really want to do this with Linq:
First of all, if you knew that you want only two levels of order, you can do something like this:
myList.Children.OrderBy(x => x.Order) .Select(c => c.Children.OrderBy(x => x.Order))
But what if you really want a completely recursive order, right up to?
delegate IEnumerable<MyType> RecursiveFunc(MyType data, RecursiveFunc self); RecursiveFunc op = (data, func) => data.Children.OrderBy(x => x.Order) .Select(x => func(x, func)); IEnumerable<MyType> result = op(myList, op);
Just writing what makes my brain hurt, and I didn’t try to run it, so I’m more lucky! It is about passing the linq (lambda) expression to itself in order to apply itself to the tree recursively.
source share