Home
Map
Count Extension MethodUse the Count extension from System.Linq to count elements with a lambda.
C#
This page was last reviewed on May 3, 2023.
Count. This C# extension method enumerates elements. In many cases, the Count() extension is not useful, but in others it is appropriate.
Most collections in C# have a Length or Count property that is more efficient. For these situations, use the property directly.
Count Array Elements
Lambda example. This is a complex example of Count(). Count() can be used with an argument of type Func. The Func can be specified with a lambda.
Func
Lambda
Here In this example we count only int elements greater than 2. The values 3, 4 and 5—three elements—are greater than 2.
using System; using System.Linq; int[] array = { 1, 2, 3, 4, 5 }; // ... Count only elements greater than 2. int greaterThanTwo = array.Count(element => element > 2); Console.WriteLine(greaterThanTwo);
3
Query example. To continue, the Count() extension is found in System.Linq. It acts upon IEnumerable—so it works on Lists and arrays, even when those types have other counting properties.
Part 1 When Count() is called on Lists or arrays, you lose some performance over calling the direct properties available.
Part 2 If you use a LINQ query expression (or have an IEnumerable instance) Count is an effective option.
IEnumerable
using System; using System.Collections.Generic; using System.Linq; int[] array = { 1, 2, 3 }; // Part 1: don't use Count() like this. // ... Use Length instead. Console.WriteLine(array.Count()); List<int> list = new List<int>() { 1, 2, 3 }; Console.WriteLine(list.Count()); // Part 2: use Count on query expression. var result = from element in array orderby element descending select element; Console.WriteLine(result.Count());
3 3 3
In benchmarks, the Length and Count properties are compared to the Count extension method. Using a property on a collection is much faster than Count.
Count Array Elements
A summary. The Count() method gets the number of elements in an IEnumerable collection. It enumerates the elements. This often is an inefficient way to get the element count of collections.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 3, 2023 (simplify).
Home
Changes
© 2007-2023 Sam Allen.