C# Enumerable Count(IEnumerable, Func)

Description

Returns a number that represents how many elements in the specified sequence satisfy a condition.

Syntax


public static int Count<TSource>(
  this IEnumerable<TSource> source,
  Func<TSource, bool> predicate
)

Parameters

  • TSource - The type of the elements of source.
  • source - A sequence that contains elements to be tested and counted.
  • predicate - A function to test each element for a condition.

Returns

returns A number that represents how many elements in the sequence satisfy the condition in the predicate function.

Example

The following code example demonstrates how to use Count(IEnumerable, Func) to count the elements in an array that satisfy a condition.


/*from   w w w .j  a  va 2  s.  c om*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  
     Pet[] pets = { new Pet { Name="A", Vaccinated=true },
                    new Pet { Name="B", Vaccinated=false },
                    new Pet { Name="C", Vaccinated=false } };

     int numberUnvaccinated = pets.Count(p => p.Vaccinated == false);
     Console.WriteLine(numberUnvaccinated);

  }
}
    
class Pet{
   public string Name { get; set; }
   public bool Vaccinated { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable