Skip to content

Instantly share code, notes, and snippets.

@lisardggY
Created July 14, 2016 13:32
Show Gist options
  • Save lisardggY/6341e31fd8f9d22f61cb3fabefce466d to your computer and use it in GitHub Desktop.
Save lisardggY/6341e31fd8f9d22f61cb3fabefce466d to your computer and use it in GitHub Desktop.
FindInTree - recursively searches a tree of objects. Expects as parameters a lambda to retrieve an item's identifier and a lambda to get a node's children.
/// <summary>
/// Recursively searches a tree structure for a specific node.
/// </summary>
/// <typeparam name="TChild">The node's type.</typeparam>
/// <typeparam name="TIdentifier">The node identifier's type</typeparam>
/// <param name="root">The root node to search under.</param>
/// <param name="identifier">The identifier of the node to find.</param>
/// <param name="childSelector">A function that returns a node's children in the tree.</param>
/// <param name="identifierSelector">A function that returns a node's identifier</param>
/// <returns>Either a <cref>TChildType</cref> instance whose identifier matches the one specified, or null if not found.</returns>
public static TChild FindInTree<TChild, TIdentifier>
(this TChild root, TIdentifier identifier, Func<TChild, IEnumerable<TChild>> childSelector, Func<TChild, TIdentifier> identifierSelector)
where TChild : class
{
if (root == null)
return null;
if (Equals(identifierSelector(root), identifier))
{
return root;
}
foreach (var child in childSelector(root))
{
var foundChild = child.FindInTree(identifier, childSelector, identifierSelector);
if (foundChild != null)
return foundChild;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment