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?
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;
}
}
}
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With