You can make this slightly more reusable by targeting the
IEnumerable<T>
interface and providing a function to return the children of each item:
public static class EnumerableExtensions
{
private static IEnumerable<T> DescendantsAndSelfIterator<T>(
IEnumerable<T> source,
Func<T, IEnumerable<T>> getChildren)
{
var queue = new Queue<IEnumerable<T>>();
queue.Enqueue(source);
while (0 != queue.Count)
{
foreach (var current in queue.Dequeue())
{
yield return current;
var children = getChildren(current);
if (null != children) queue.Enqueue(children);
}
}
}
public static IEnumerable<T> DescendantsAndSelf<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> getChildren)
{
if (null == source) throw new ArgumentNullException("source");
if (null == getChildren) return source;
return DescendantsAndSelfIterator(source, getChildren);
}
}
Your
TreeView
extension method then becomes:
public static class TreeViewExtension
{
public static IEnumerable<TreeNode> AllTreeNodes(this TreeView treeView)
{
if (null == treeView) throw new ArgumentNullException("treeView");
return treeView.Nodes.Cast<TreeNode>()
.DescendantsAndSelf(n => n.Nodes.Cast<TreeNode>());
}
}