21

An array is defined of assumed elements like I have array like String[] strArray = new String[50];.

Now from 50 elements only some elements are assigned and remaining are left null then I want the number of assigned elements.

Like here only 30 elements are assigned then I want that figure.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
Harikrishna
  • 4,185
  • 17
  • 57
  • 79

3 Answers3

33

You can use Enumerable.Count:

string[] strArray = new string[50];
...
int result = strArray.Count(s => s != null);

This extension method iterates the array and counts the number of elements the specified predicate applies to.

dtb
  • 213,145
  • 36
  • 401
  • 431
  • 3
    The code uses LINQ. You need to add `using System.Linq;` at the top of your source file to make the LINQ extension methods visible. – dtb Mar 06 '10 at 09:28
  • Is it same to do like everytime checking for the each element of strArray that it is null or not in the for loop ? – Harikrishna Mar 06 '10 at 09:38
  • To "right fit" the Array to include only those assigned elements, I found [this](http://stackoverflow.com/a/9571134/307454) helpful. – lifebalance Nov 04 '13 at 19:59
8

Using LINQ you can try

int count = strArray.Count(x => x != null);
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
1

Use LINQ:

int i = (from s in strArray where !string.IsNullOrEmpty(s) select s).Count();
slugster
  • 49,403
  • 14
  • 95
  • 145