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
{
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>(
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());
}
}
source
share