An int that contains the number of elements in the sequence.
This method is typically used to get the number of elements in a collection. For collections that implement ICollection<T>, the Count property is used. Otherwise, this method iterates through the sequence to count the elements.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
// Using a List
List<int> numbersList = new List<int> { 1, 2, 3, 4, 5 };
int countList = numbersList.Count();
Console.WriteLine($"Count of list: {countList}"); // Output: Count of list: 5
// Using an array
int[] numbersArray = { 10, 20, 30 };
int countArray = numbersArray.Count();
Console.WriteLine($"Count of array: {countArray}"); // Output: Count of array: 3
// Using a LINQ query result
var query = from num in numbersList
where num % 2 == 0
select num;
int countQuery = query.Count();
Console.WriteLine($"Count of even numbers: {countQuery}"); // Output: Count of even numbers: 2
}
}
An int that contains the number of elements in the sequence that satisfy the condition.
This overload allows you to count elements that meet a specific criteria defined by the predicate. The predicate is applied to each element, and only elements for which the predicate returns true are counted.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Count even numbers
int evenCount = numbers.Count(n => n % 2 == 0);
Console.WriteLine($"Number of even numbers: {evenCount}"); // Output: Number of even numbers: 5
// Count numbers greater than 5
int greaterThanFiveCount = numbers.Count(n => n > 5);
Console.WriteLine($"Number of elements greater than 5: {greaterThanFiveCount}"); // Output: Number of elements greater than 5: 5
// Count strings that start with 'A'
List<string> names = new List<string> { "Alice", "Bob", "Anna", "Charlie" };
int startsWithACount = names.Count(s => s.StartsWith("A"));
Console.WriteLine($"Number of names starting with 'A': {startsWithACount}"); // Output: Number of names starting with 'A': 2
}
}