Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Conversion Operators

Method-Based Query Syntax Examples: Conversion Operators (LINQ to DataSet)

The examples in this topic demonstrate how to use the ToArray<TSource>, ToDictionary, and ToList<TSource> methods to immediately execute a query expression.

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 uses the ToArray<TSource> method to immediately evaluate a sequence into an array.

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

DataTable products = ds.Tables["Product"];

IEnumerable<DataRow> productsArray = products.AsEnumerable().ToArray();

IEnumerable<DataRow> query =
    from product in productsArray
    orderby product.Field<Decimal>("ListPrice") descending 
    select product;

Console.WriteLine("Every price from highest to lowest:");
foreach (DataRow product in query)
{
    Console.WriteLine(product.Field<Decimal>("ListPrice"));
}

This example uses the ToDictionary method to immediately evaluate a sequence and a related key expression into a dictionary.

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

DataTable products = ds.Tables["Product"];


var scoreRecordsDict = products.AsEnumerable().
    ToDictionary(record => record.Field<string>("Name"));
Console.WriteLine("Top Tube's ProductID: {0}",
    scoreRecordsDict["Top Tube"]["ProductID"]);

This example uses the ToList<TSource> method to immediately evaluate a sequence into a List<T>, where T is of type DataRow.

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

DataTable products = ds.Tables["Product"];

IEnumerable<DataRow> productList = products.AsEnumerable().ToList();

IEnumerable<DataRow> query =
    from product in productList
    orderby product.Field<string>("Name")
    select product;

Console.WriteLine("The product list, ordered by product name:");
foreach (DataRow product in query)
{
    Console.WriteLine(product.Field<string>("Name").ToLower(CultureInfo.InvariantCulture));
}
Show:
© 2015 Microsoft