Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we find items count in the C# integer array?

I need to find items count in the C# array which type is integer.

What I mean is;

int[] intArray=new int[10]
int[0]=34
int[1]=65
int[2]=98

Items count for intArray is 3.

I found the code for strArray below but It doesn't work for int arrays.

string[] strArray = new string[50];
...
int result = strArray.Count(s => s != null);
like image 222
Ned Avatar asked Jun 05 '12 23:06

Ned


1 Answers

Well, first you have to decide what an invalid value would be. Is it 0? If so, you could do this:

int result = intArray.Count(i => i != 0);

Note that this only works because, by default, elements of an int array are initialized to zero. You'd have to fill the array with a different, invalid value beforehand if 0 ends up being valid in your situation.

Another way would be to use a nullable type:

int?[] intArray = new int?[10];
intArray[0] = 34;
intArray[1] = 65;
intArray[2] = 98;

int result = intArray.Count(i => i.HasValue);
like image 95
itsme86 Avatar answered Oct 21 '22 12:10

itsme86