Home » Development » How to find actual item count in the C# array?

How to find actual item count in the C# array?

We use arrays to hold more than 1 values at programming languages. For this reason, we need a lot of array methods like counting items. There is a simple method to find how many items an array has out:

string[] strArray = new string[50];
strArray[0] = "a";
strArray[1] = "b";
strArray[2] = "c";
strArray[3] = "d";
int result = strArray.Length;

result variable takes 50. This is the number that shows how many values the array can hold but we need how many values the array actually hold? We need 4 instead of 50.

Here is the code for our purpose:

int result = strArray.Count(s => s != null);

If you use integer array, It would be:

int?[] intArray = new int?[30];
intArray[0] = 5;
intArray[1] = 15;
int result2 = intArray.Count(i => i.HasValue);

More information: 

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment