以方法為基礎的查詢語法範例:項目運算子 (LINQ to DataSet)
此主題中的範例將示範如何使用 First 和 ElementAt 方法並搭配查詢運算式語法來取得 DataRow 中的 DataSet 項目。
將資料載入 DataSet 中指定了這些範例使用的 FillDataSet
方法。
此主題中的範例將使用 AdventureWorks 範例資料庫中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 資料表。
此主題中的範例使用下列 using
/Imports
陳述式:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
Option Explicit On
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Globalization
如需詳細資訊,請參閱操作說明:在 Visual Studio 中建立 LINQ to DataSet 專案。
ElementAt
範例
這則範例會使用 ElementAt 方法來擷取 PostalCode
== "M4B 1V7" 的第五筆地址。
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
DataTable addresses = ds.Tables["Address"];
var fifthAddress = (
from address in addresses.AsEnumerable()
where address.Field<string>("PostalCode") == "M4B 1V7"
select address.Field<string>("AddressLine1"))
.ElementAt(5);
Console.WriteLine("Fifth address where PostalCode = 'M4B 1V7': {0}",
fifthAddress);
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)
Dim addresses As DataTable = ds.Tables("Address")
Dim fifthAddress = ( _
From address In addresses.AsEnumerable() _
Where address.Field(Of String)("PostalCode") = "M4B 1V7" _
Select address.Field(Of String)("AddressLine1")).ElementAt(5)
Console.WriteLine("Fifth address where PostalCode = 'M4B 1V7': " & _
fifthAddress)
First
範例
這則範例會使用 First 方法來傳回名字為 'Brooke' 的第一位連絡人。
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
DataTable contacts = ds.Tables["Contact"];
DataRow query = (
from contact in contacts.AsEnumerable()
where (string)contact["FirstName"] == "Brooke"
select contact)
.First();
Console.WriteLine("ContactID: " + query.Field<int>("ContactID"));
Console.WriteLine("FirstName: " + query.Field<string>("FirstName"));
Console.WriteLine("LastName: " + query.Field<string>("LastName"));
' Fill the DataSet.
Dim ds As New DataSet()
ds.Locale = CultureInfo.InvariantCulture
' See the FillDataSet method in the Loading Data Into a DataSet topic.
FillDataSet(ds)
Dim contacts As DataTable = ds.Tables("Contact")
Dim query = ( _
From contact In contacts.AsEnumerable() _
Where contact.Field(Of String)("FirstName") = "Brooke" _
Select contact).First()
Console.WriteLine("ContactID: " & query.Field(Of Integer)("ContactID"))
Console.WriteLine("FirstName: " & query.Field(Of String)("FirstName"))
Console.WriteLine("LastName: " & query.Field(Of String)("LastName"))