There are several ways to solve this problem.
Firstly, you can implement the method, i.e. AsFlattenEnumerable . Imaging, you have a Tree<T> class that has node data of type T
Declare a Flatten<T> class:
public Flatten<T> { public T Data { get; } public int Level { get; } }
Then do AsFlattenEnumerable :
public class Tree<T> { . . . public IEnumerable<Flatten<T>> AsFlattenEnumerable() { . . . } . . . }
Now you can sort the nodes with a simple LINQ query:
var ordereNodes = from node in tree.AsFlattenEnumerable() // Fe first Level, then A, then B order node by new { node.Level, node.Data.A, node.Data.B };
Secondly, the C # compiler allows you to declare your own methods for the order by clause (and the OrderBy method, of course).
Imaging, you have a Tree<T> class that implements the ITreeEnumerable<T> interface (there is a similar hierarchical interface in the System.Web assembly).
You can then define your own extension methods, such as Where and OrderBy :
public static ITreeEnumerable<TSource> OrderBy<TSource, TKey>(this ITreeEnumerable<TSource> source, Func<TSource, TKey> keySelector) { . . . }
Now you can sort your enums using LINQ:
var orderedNodes = from node in tree // tree implements ITreeEnumerable<T> // First Level (by default), then custom ordering by A and B order by new { node.A, node.B }; . . . var enumerableNodes = orderedNodes.AsEnumerable();
The C # compiler converts this expression:
var result = from i in obj order i by i.Foo;
:
var result = obj.OrderBy(i => i.Key);
The obj variable can be of any type, not necessarily IEnumerable . The obj type must have an OrderBy method, or you can implement an extension method.