Very small, simple and extremely useful method:
public static IEnumerable<T> EnumerateChain<T>(this T start, Func<T, T> next) where T : class { while (start != null) { yield return start; start = next(start); } }
How to use it you may ask. Suppose (just for the sake of example) you have some tree structure, with Name
and Parent
properties in each node. And you want to get path in tree of some given node in form of node names separated by slashes. Nothing could be easier:
public static string GetPathInTree(Node node) { var names = node.EnumerateChain(n => n.Parent).Reverse().Select(n => n.Name); return String.Join("/", names); }
Basically with this method you can traverse any structure as if it was normal IEnumerable. Very convenient, really 🙂
C# is awesome 🙂 one can extend it in so many elegant ways!
Comment by Patrick Smacchia — 20/02/2013 @ 10:58