简体   繁体   中英

Count list of items that contain a list of the same items

Let's say I have a class that contains a List with any number of items. Within each of those Lists it can contain a List of that same class of lists. Also it contains another list of another class. I want to count the number of that last type of list overall. OK that wasn't clear. I'll provide the skeleton code:

public class A
{
    public List<B> bs{ get; set; }

    public int CountCs()
    {

    }
}

public class B
{
    public List<B> Bs{ get; set; }
    public List<C> Cs{ get; set; }
}

public class C
{

}

I want to write the CountCs function so that I get the total count of Cs through the whole instance of A. I've played around with recursive functions and whatnot but now my brain has imploded. Any ideas?

Let the B class count its own collection of C. As part of the work, it could iterate through each B (if any) in its own collection of B, and each of those would return a count too, and on and on...

public class B
{
    public List<B> Bs { get; set; }
    public List<C> Cs { get; set; }

    public int TotalCs()
    {
        var subtotal = Bs != null ? Bs.Sum(b => b.TotalCs()) : 0;

        return subtotal + Cs.Count;
    }
}

Kick it off by calling it from your instance of A:

public class A
{
    public List<B> bs { get; set; }

    public int CountCs()
    {
        return bs.Sum(b => b.TotalCs());
    }
}

Finally:

var a = new A();

... // add a bunch of Bs and Cs

var totalCs = a.CountCs();

See it in action: https://ideone.com/r1gGnE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM