返回序列中的第一个元素

使用 First 运算符可返回序列中的第一个元素。 使用 First 的查询是立即执行的。

注意

LINQ to SQL 不支持 Last 运算符。

示例 1

下面的代码查找表中的第一个 Shipper

如果您对 Northwind 示例数据库运行此查询,则结果为

ID = 1, Company = Speedy Express

Shipper shipper = db.Shippers.First();
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID,
    shipper.CompanyName);
Dim shipper As Shipper = db.Shippers.First()
Console.WriteLine("ID = {0}, Company = {1}", shipper.ShipperID, _
        shipper.CompanyName)

示例 2

下面的代码查找具有 Customer BONAP 的单个 CustomerID

如果您对 Northwind 示例数据库运行此查询,则结果为 ID = BONAP, Contact = Laurence Lebihan

Customer custQuery =
    (from custs in db.Customers
    where custs.CustomerID == "BONAP"
    select custs)
    .First();

Console.WriteLine("ID = {0}, Contact = {1}", custQuery.CustomerID,
    custQuery.ContactName);
Dim custquery As Customer = _
    (From c In db.Customers _
     Where c.CustomerID = "BONAP" _
     Select c) _
    .First()

Console.WriteLine("ID = {0}, Contact = {1}", custquery.CustomerID, _
    custquery.ContactName)

请参阅