Count the Number of Elements in a Sequence

Use the Count operator to count the number of elements in a sequence.

Running this query against the Northwind sample database produces an output of 91.

Example 1

The following example counts the number of Customers in the database.

System.Int32 customerCount = db.Customers.Count();
Console.WriteLine(customerCount);
Dim customerCount = db.Customers.Count()
Console.WriteLine(customerCount)

Example 2

The following example counts the number of products in the database that have not been discontinued.

Running this example against the Northwind sample database produces an output of 69.

System.Int32 notDiscontinuedCount =
    (from prod in db.Products
    where !prod.Discontinued
    select prod)
    .Count();

Console.WriteLine(notDiscontinuedCount);
Dim notDiscontinuedCount = Aggregate prod In db.Products _
                           Into Count(Not prod.Discontinued)

Console.WriteLine(notDiscontinuedCount)

See also