Count

Ever need to find out how many items there are in a list or array without using a for loop? Sure, you can use the .Length, but what if was a list? Well, you can use the .Count method.

Basic example

Live example: https://dotnetfiddle.net/mEnmqd

var scores = new[] { 2, 4, 6, 8, 10 };

var scoreCount = scores.Count();

//output: 5

Count with Func

If you ever need to count items based on a particular condition, you can use a Func within the Count method.

Let's say we want to count all numbers that are not negative, in other words, only positive numbers.

We use a Func where it returns a boolean value. In this case we want to only bring back positive numbers, so we can just use the greater than comparison.

Live example: https://dotnetfiddle.net/BJDDiA

var scores = new[] { 87, 56, 33, 20, 11, -10, -50 };

var numnerOfScoresThatAreNotNegative = scores.Count(i => i > 0);

// output 5