Skip to content

Instantly share code, notes, and snippets.

@Larry57
Created June 3, 2011 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Larry57/1006356 to your computer and use it in GitHub Desktop.
Save Larry57/1006356 to your computer and use it in GitHub Desktop.
Ancestors and Descendants for Tree handling
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