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