Question

I've got a simple class defined as:

public class MyClass
{
   //Some properties
   public List<MyClass> SubEntries { get; set; }
   //Some more properties
}

In another class I have a list of the above type. At the moment, I'm having a serious mental block. I just need to itereate through the list and count all occurances of MyClass. Since the SubEntries property can contain 0 or more entries which can themselves contain 0 or more entries, it strikes me that I need some sort of recursice method, unless LINQ provides a mechanism to do this.

Any help releasing this mental log jam would be appreciated.

Was it helpful?

Solution

Assuming you don't mind recursing down the tree, and assuming the list is always non-null and doesn't have cycles:

public class MyClass
{
    public List<MyClass> SubEntries { get; set; }

    public int SubEntryCount
    {
        get { return 1 + SubEntries.Sum(x => x.SubEntryCount); }
    }
}

You may want to rename it so that it's clear it's a total count of sub-entries, not just immediate children.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top