I needed a quick and dirty method to count an array, but only select if the element contained a value. After a little bit of tinkering I came up with this:
int count = 0;
for (int i = 0; i < array.Length; i++)
{
if (array[i] != null)
count++;
}
return count;
Really, a quick method to overcome this issue with no useless details - Then after searching stackoverflow I noticed that this question was asked before: Count non null elements in an array of lists
A very elegant answer: Use Enumerable.Count()
! The mighty gods of computer land gave us this precious tool called LINQ and I think we are using it more than we should.
array.Count(x => x != null)
Looks very sweet and easy to understand
To test its performance I created an 100 million element array containing "yes" string but only leaving 1 out. After running the test with Stopwatch class, the results were quite surprising:
Enumerable.Count: ~600 ms A dirty code block: ~60 ms
A very big difference when it comes to repetitive execution. What might be the reason behind this? I don't think that any engineer in Microsoft is as stupid as me.