共用方式為


查詢運算式語法範例:項目運算子

本主題中的範例示範如何使用 First 方法,透過查詢運算式語法來查詢 AdventureWorks Sales Model。 這些範例中使用的 AdventureWorks Sales Model 是從 AdventureWorks 範例資料庫中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 資料表所建立。

此主題中的範例使用下列 using/Imports 陳述式:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Globalization;
using System.Data.EntityClient;
using System.Data.SqlClient;
using System.Data.Common;

Option Explicit On
Option Strict On
Imports System.Data.Objects
Imports System.Globalization

First

範例

下列範例會使用 First 方法來傳回名字為 "Brooke" 的第一位連絡人。

string firstName = "Brooke";
using (AdventureWorksEntities context = new AdventureWorksEntities())
{
    ObjectSet<Contact> contacts = context.Contacts;

    Contact query = (
        from contact in contacts
        where contact.FirstName == firstName
        select contact)
        .First();

    Console.WriteLine("ContactID: " + query.ContactID);
    Console.WriteLine("FirstName: " + query.FirstName);
    Console.WriteLine("LastName: " + query.LastName);
}
Dim firstName = "Brooke"
Using context As New AdventureWorksEntities
    Dim contacts As ObjectSet(Of Contact) = context.Contacts

    Dim query As Contact = ( _
        From cont In contacts _
        Where cont.FirstName = firstName _
        Select cont).First()

    Console.WriteLine("ContactID: " & query.ContactID)
    Console.WriteLine("FirstName: " & query.FirstName)
    Console.WriteLine("LastName: " & query.LastName)
End Using

另請參閱