简体   繁体   中英

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

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.

如果您要计算Rd中的所有Bn,请使用SelectMany()

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

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))));

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