Checking tree length using linq

Hi, let's say I have a tree of the following type

public class Element
{
    public List<Element> element;
}

lets say that the root of the tree

Element root = GetTree();

I know that it is possible to check the length of this tree using recursion, but is it possible to check the length of this tree using linq?

+5
source share
3 answers

You can write an extension method to recursively extract all the elements.

var allElements = root.element.Traverse(el => el.element);

For instance:

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

        IEnumerable<T> seqRecurse = fnRecurse(item);
        if (seqRecurse != null)
        {
            foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))
            {
                yield return itemRecurse;
            }
        }
    }
}
+2
source

Add a new extension method;

    public static int CountX(this Element e)
    {
        int temp = 0;
        if (e.element != null)
        {
            temp = e.element.Count;
            e.element.ForEach(q => temp += q.CountX());
        }
        return temp;
    }

and name it like this:

int depthCount= a.CountX();
+1
source

As far as I know, you cannot have a returnable Linq, because having recursive lambdas is not possible out of the box.

The most original answer I can give is based on a recursive lambda expression based on a multiple Fixpoint statement. You will find most Linq gears. But I'm afraid that the fixpoint part is the reason that there is no pure Linq answer.

public static class FixPoint
{
    // Reusable fixpoint operator
    public static Func<T, TResult> Fix<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> f)
    {
        return t => f(Fix<T, TResult>(f))(t);
    }
}

public class Element
{
    public List<Element> element;


    public int CalculateMaxDepth()
    {
        return FixPoint.Fix<List<Element>, int>(
            // recursive lambda
            f =>
            listElement => listElement == null || listElement.Count == 0 
                ? 0 
                : 1 + listElement.Select(e => f(e.element)).Max())
            (this.element);
    }

    [Test]
    public  void myTest()
    {
        var elt = new Element() { element = new List<Element> { new Element() { element = new List<Element> { new Element() { element = new List<Element> { new Element() } } } } } };
        Assert.AreEqual(3, elt.CalculateMaxDepth());
    }
}
+1
source

All Articles