如何:对序列中的元素进行计数 (LINQ to SQL)

使用 Count 运算符可计算序列中的元素数目。

对 Northwind 示例数据库运行此查询产生的输出为 91。

示例

下面的示例计算数据库中的 Customers 数目。

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

下面的示例计算数据库中尚未停产的产品数目。

对 Northwind 示例数据库运行此示例产生的输出为 69。

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

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

Console.WriteLine(notDiscontinuedCount);

请参见

概念

下载示例数据库 (LINQ to SQL)

其他资源

聚合查询 (LINQ to SQL)