2

I couldn't find this anywhere else. I've an array of lists:

public List<xmldata>[] XMLArrayList = new List<xmldata>[9999];

To initialize and insert a list into each position, i do the following:

for(int m=0; m< XList.XMLArrayList.Count(); m++)
{
    XList.XMLArrayList[m] = new List<xmldata>();
}

But i would like to count how many elements there aren't null. EX: Positions 0 to 5 have a List on them. But other positions not.

Tried a linq approach:

int count = XList.XMLArrayList.Count(x => x != null);

But it returns me the array size (9999). How can i count the non null elements on an array of lists ? Ps: Already tried Dictionary and And List of List - this approach works best for achieving what i need.

Thanks.

MethodMan
  • 18,625
  • 6
  • 34
  • 52
Pablo Costa
  • 125
  • 4
  • 14

2 Answers2

5

Try this:

int count = XList.XMLArrayList.Count(x => x.Count()>0);
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • Exactly ! WOrked as expected. Thanks. – Pablo Costa Feb 25 '16 at 19:44
  • 1
    Since these are lists you can use the `Count` property instead of the `Count()` extension method. – juharr Feb 25 '16 at 19:46
  • 2
    This is slightly cleaner: `XList.XMLArrayList.Count(c => c.Any());` – S. Brentson Feb 25 '16 at 19:49
  • 3
    Checking for non-empty collections is more ideomatically done using `enumeration.Any()` rather than `enumeration.Count() > 0`. it is also faster (O(1) vs O(n)). if Count() is evaluated on a heavy sql query it'll be very expensive. `Any()` will just check if enumerating yields an element and then return, regardless of the size of the enumeration. – sara Feb 25 '16 at 19:52
  • @kai, Since these are lists the `Count()` extenstion method will just end up returning the `Count` property value which is O(1). – juharr Feb 25 '16 at 19:57
  • @juharr that's true I guess, I'd still argue it's more correct, both from a semantic and from a maintainability point of view to use `Any` when checking for emptyness, even if the practical difference is negligible in this case (good habits and all that) – sara Feb 25 '16 at 19:59
0

you can also do this

XList.XMLArrayList.Where(x => x.Any()).Count();
Viru
  • 2,228
  • 2
  • 17
  • 28