共用方式為


資料集專屬運算子範例 (LINQ to DataSet)

此主題中的範例將示範如何使用 CopyToDataTable 方法和 DataRowComparer 類別 (Class)。

將資料載入資料集中指定了這些範例使用的 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 專案

CopyToDataTable

範例

這則範例會使用 DataTable 方法來載入含有查詢結果的 CopyToDataTable

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

DataTable contacts1 = ds.Tables["Contact"];

IEnumerable<DataRow> query =
    from contact in contacts1.AsEnumerable()
    where contact.Field<string>("Title") == "Ms."
        && contact.Field<string>("FirstName") == "Carla"
    select contact;

DataTable contacts2 = query.CopyToDataTable();

foreach (DataRow contact in contacts2.AsEnumerable())
{
    Console.WriteLine("ID:{0} Name: {1}, {2}",
        contact.Field<Int32>("ContactID"),
        contact.Field<string>("LastName"),
        contact.Field<string>("FirstName"));
}
' 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 contactTable As DataTable = ds.Tables("Contact")

Dim query = _
    From contact In contactTable.AsEnumerable() _
    Where contact.Field(Of String)("Title") = "Ms." _
            And contact.Field(Of String)("FirstName") = "Carla" _
    Select contact

Dim contacts = query.CopyToDataTable().AsEnumerable()

For Each contact In contacts
    Console.Write("ID: " & contact.Field(Of Integer)("ContactID"))
    Console.WriteLine(" Name: " & contact.Field(Of String)("LastName") & _
                      ", " & contact.Field(Of String)("FirstName"))
Next

DataRowComparer

範例

這則範例會使用 DataRowComparer 來比較兩個不同的資料列。

// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);

// Get two rows from the SalesOrderHeader table.
DataTable table = ds.Tables["SalesOrderHeader"];
DataRow left = (DataRow)table.Rows[0];
DataRow right = (DataRow)table.Rows[1];

// Compare the two different rows.
IEqualityComparer<DataRow> comparer = DataRowComparer.Default;

bool bEqual = comparer.Equals(left, right);
if (bEqual)
    Console.WriteLine("The two rows are equal");
else
    Console.WriteLine("The two rows are not equal");

// Get the hash codes of the two rows.
Console.WriteLine("The hashcodes for the two rows are {0}, {1}",
    comparer.GetHashCode(left),
    comparer.GetHashCode(right));

另請參閱