How to Use LINQ Count in C# - Simple Guide
Use
Count() from LINQ in C# to count elements in a collection. You can call Count() without parameters to get the total number of items, or pass a condition as a lambda expression to count only items that match it.Syntax
The Count() method has two common forms:
collection.Count(): Counts all elements in the collection.collection.Count(condition): Counts elements that satisfy thecondition(a lambda expression returning true or false).
This method is part of the System.Linq namespace.
csharp
int total = collection.Count(); int filtered = collection.Count(item => item.Property == value);
Example
This example shows how to count all numbers in a list and how to count only even numbers using LINQ Count().
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 }; int totalCount = numbers.Count(); int evenCount = numbers.Count(n => n % 2 == 0); Console.WriteLine($"Total numbers: {totalCount}"); Console.WriteLine($"Even numbers: {evenCount}"); } }
Output
Total numbers: 6
Even numbers: 3
Common Pitfalls
Common mistakes when using Count() include:
- Forgetting to include
using System.Linq;which causesCount()to be unavailable. - Using
Count()on large collections repeatedly inside loops, which can hurt performance because it enumerates the collection each time. - Confusing
Count()withLengthorCountproperty on arrays or lists;Count()is a method from LINQ and works on anyIEnumerable.
Wrong:
var count = myList.Count; // works only if myList is List or array var count = myEnumerable.Count; // error if myEnumerable is IEnumerable without Count property
Right:
using System.Linq; var count = myEnumerable.Count();
Quick Reference
LINQ Count Cheat Sheet:
| Usage | Description |
|---|---|
collection.Count() | Count all elements |
collection.Count(x => x > 10) | Count elements matching condition |
using System.Linq; | Required namespace |
| Usage | Description |
|---|---|
| collection.Count() | Count all elements |
| collection.Count(x => x > 10) | Count elements matching condition |
| using System.Linq; | Required namespace |
Key Takeaways
Always include 'using System.Linq;' to use LINQ Count.
Use Count() without parameters to count all items in a collection.
Use Count(condition) with a lambda to count items that meet a condition.
Avoid calling Count() repeatedly on large collections inside loops for better performance.
Count() works on any IEnumerable, unlike Count property which is only on some collections.