Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to count all items in Hierachical object list

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.

like image 920
Steve Brouillard Avatar asked Dec 22 '22 11:12

Steve Brouillard


1 Answers

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.

like image 57
Jon Skeet Avatar answered Dec 28 '22 15:12

Jon Skeet