查詢運算式語法範例:元素運算子 (LINQ to DataSet)
此主題中的範例將示範如何使用 First 和 ElementAt<TSource> 方法並搭配查詢運算式語法來取得 DataSet 中的 DataRow 項目。
在這些範例中使用的 FillDataSet 方法指定於將資料載入 DataSet。
此主題中的範例將使用 AdventureWorks 範例資料庫中的 Contact、Address、Product、SalesOrderHeader 和 SalesOrderDetail 資料表。
此主題中的範例將使用下列 using/Imports 陳述式:
Option Explicit On
Imports System
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
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Globalization;
如需詳細資訊,請參閱 HOW TO:在 Visual Studio 中建立 LINQ to DataSet 專案。
ElementAt
範例
這則範例會使用 ElementAt<TSource> 方法來擷取 PostalCode == "M4B 1V7" 的第五筆地址。
' 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)
// 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);
First
範例
這則範例會使用 First 方法來傳回名字為 'Brooke' 的第一位連絡人。
' 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"))
// 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"));