C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: When Count() is called on Lists or arrays, you lose some performance over calling the direct properties available.
Important: If you use a LINQ query expression (or have an IEnumerable instance) Count is an effective option.
IEnumerableC# program that uses Count extension
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3 };
// Don't use Count() like this! Use Length.
Console.WriteLine(array.Count());
List<int> list = new List<int>() { 1, 2, 3 };
// Don't use Count() like this! Use Count property.
Console.WriteLine(list.Count());
var result = from element in array
orderby element descending
select element;
// Good.
Console.WriteLine(result.Count());
}
}
Output
3
3
3
C# program that uses Count with argument
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5 };
// ... Count only elements greater than 2.
int greaterThanTwo = array.Count(element => element > 2);
Console.WriteLine(greaterThanTwo);
}
}
Output
3