Edit

Share via


Query Expression Syntax Examples: Element Operators (LINQ to DataSet)

The examples in this topic demonstrate how to use the First and ElementAt methods to get DataRow elements from a DataSet using the query expression syntax.

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:

C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;

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

ElementAt

Example

This example uses the ElementAt method to retrieve the fifth address where PostalCode == "M4B 1V7".

C#
// 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': {fifthAddress}");

First

Example

This example uses the First method to return the first contact whose first name is 'Brooke'.

C#
// 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"));

See also