Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking length of tree using linq

Tags:

c#

linq

tree

Hi lets say i have tree of following type

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

lets say root of the tree is

Element root = GetTree();

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

like image 772
kosnkov Avatar asked Oct 06 '22 00:10

kosnkov


2 Answers

You could write an extension method to retrieve all elements recursively.

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

For example:

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;
            }
        }
    }
}
like image 108
Tim Schmelter Avatar answered Oct 09 '22 18:10

Tim Schmelter


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 call it like;

int depthCount= a.CountX();
like image 32
daryal Avatar answered Oct 09 '22 18:10

daryal