How many elements of array are not null?

31,687

Solution 1

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.

Solution 2

Using LINQ you can try

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

Solution 3

Use LINQ:

int i = (from s in strArray where !string.IsNullOrEmpty(s) select s).Count();
Share:
31,687
Harikrishna
Author by

Harikrishna

I am a M.C.A. student in Gujrat,India. And my e-mail address is [email protected]. I am doing my training in winform for my sixth semester of M.C.A.

Updated on July 09, 2022

Comments

  • Harikrishna
    Harikrishna almost 2 years

    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.

  • slugster
    slugster about 14 years
    You beat my 5.37 seconds :) But does the OP want null or non null elements?
  • Feidex
    Feidex about 14 years
    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.
  • Harikrishna
    Harikrishna about 14 years
    Is it same to do like everytime checking for the each element of strArray that it is null or not in the for loop ?
  • slugster
    slugster about 14 years
    Mmmmm thanks?!?! The other guys had more concise answers than me.
  • lifebalance
    lifebalance over 10 years
    To "right fit" the Array to include only those assigned elements, I found this helpful.