DataSet-Specific Operator Examples (LINQ to DataSet)


The examples in this topic demonstrate how to use the CopyToDataTable<T> method and the DataRowComparer class.

The FillDataSet method used in these examples is specified in Loading Data Into a DataSet.

The examples in this topic use the Contact, Address, Product, SalesOrderHeader, and SalesOrderDetail tables in the AdventureWorks sample database.

The examples in this topic use the following using/Imports statements:

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;

For more information, see How to: Create a LINQ to DataSet Project In Visual Studio.

This example loads a DataTable with query results by using the CopyToDataTable<T> method.

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

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}",

This example compares two different data rows by using DataRowComparer.

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

// 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");
    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}",