recursive linq in csharp

Here is an example of how to use recursive LINQ queries in C# using lambda expressions:

main.cs
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector)
{
    foreach (T item in source)
    {
        yield return item;

        IEnumerable<T> children = childrenSelector(item);

        if (children != null)
        {
            foreach (T child in children.Traverse(childrenSelector))
            {
                yield return child;
            }
        }
    }
}
428 chars
18 lines

This extension method can be used to recursively traverse a tree-like structure in LINQ. Here is an example of how to use the method:

main.cs
public class Node
{
    public int Id { get; set; }
    public List<Node> Children { get; set; }
}

List<Node> nodes = new List<Node>
{
    new Node
    {
        Id = 1,
        Children = new List<Node>
        {
            new Node { Id = 2 },
            new Node
            {
                Id = 3,
                Children = new List<Node>
                {
                    new Node { Id = 4 },
                    new Node { Id = 5 }
                }
            }
        }
    },
    new Node { Id = 6 }
};

IEnumerable<Node> result = nodes.Traverse(n => n.Children);

foreach (Node node in result)
{
    Console.WriteLine(node.Id);
}
652 chars
35 lines

This will output the following:

main.cs
1
2
3
4
5
6
12 chars
7 lines

Here, Traverse is called on the nodes collection, specifying that the Children property should be used to generate the child nodes. The resulting IEnumerable<Node> contains all nodes in the tree. The foreach loop then iterates over each node, printing its Id property.

gistlibby LogSnag