Created
June 3, 2011 13:39
-
-
Save Larry57/1006356 to your computer and use it in GitHub Desktop.
Ancestors and Descendants for Tree handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
public static class Extensions | |
{ | |
static public IEnumerable<T> Descendants<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> descendBy) | |
{ | |
foreach (T value in source) | |
{ | |
yield return value; | |
foreach (T child in descendBy(value).Descendants<T>(descendBy)) | |
{ | |
yield return child; | |
} | |
} | |
} | |
static public IEnumerable<T> Ancestors<T>(this T source, Func<T, T> parentOf) | |
{ | |
var Parent = parentOf(source); | |
while (Parent != null) | |
{ | |
yield return Parent; | |
Parent = parentOf(Parent); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment