user1392853
user1392853

Reputation: 269

How can I count all items in multi-level list in linq

I have multi-level list like this

public class Rd {
        public List<Ru> Ru = new List<Ru>();
    }
    public class Ru {
        public List<Rc> Rc = new List<Rc>();
    }
    public class Rc {
        public List<Rcp> Rcp = new List<Rcp>();
    }
    public class Rcp {
        public string Bn { get; set; }
    }

How can i count all item in this multi-level list use linq

Which better between linq and foreach in this situation

Upvotes: 0

Views: 1540

Answers (3)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

you may want to check how many strings are in this nested list?

        List<Rd> a = YourList;

        int count =
            (from rd in a        // foreach (Rd rd in a)
             from ru in rd.Ru    // foreach (Ru ru in rd.Ru)
             from rc in ru.Rc    // foreach (Rc rc in ru.Rc)
             from rcp in rc.Rcp  // foreach (Rcp rcp in rc.Rcp)
             select rcp)         // select rcp`s
             .Count(rcp => rcp.Bn != null); // Count if rcp != null

But if you want to count the lists too you must use this.

        int countAll = a.Sum(rd =>
                       rd.Ru.Sum(ru =>
                       ru.Rc.Sum(rc =>
                       rc.Rcp.Count(rcp =>
                       rcp.Bn != null) + 1) + 1) + 1);

I flipped + operands so it may be more clear.

You have to add 1 for every list you look into. So:

        int countAll = a.Sum(rd => // foreach (Rd rd in a) add 1 to next Sum
                       1 + rd.Ru.Sum(ru => // foreach (Ru ru in rd.Ru) add 1 to next Sum
                           1 + ru.Rc.Sum(rc => // foreach (Rc rc in ru.Rc) add 1 to next Count
                               1  + rc.Rcp.Count(rcp => // Count rcp`s  if rcp != null
                                   rcp.Bn != null))));

You can add more list your self if you learn this algorithm.

Upvotes: 1

RB1987
RB1987

Reputation: 55

If you need to also check all instances where strings are not null or empty

Rd pack = new Rd();
int x = pack.Ru.Sum(node => node.Rc.Sum(cnode => cnode.Rcp.Count(ccnode => !String.IsNullOrWhiteSpace(ccnode.Bn))));

Upvotes: 0

Cologler
Cologler

Reputation: 724

if you mean count all Bn in Rd, use SelectMany():

rd.SelectMany(z => Ru).SelectMany(z => Rc).SelectMany(z => Rcp).Count()

Upvotes: 0

Related Questions