6.14. Exporting the Results of a Query to an Array

Problem

You need to export the results of a query to an array in a manner similar to the GetRows() method of the ADO Recordset.

Solution

Use a routine that mimics the functionality of the ADO Recordset's GetRows() method.

The solution creates a DataTable that contains data from the Person.Contact table in AdventureWorks. The custom GetRows() method in this solution is called to convert the DataTable into an array similar to one that is generated by the GetRows() method of the ADO Recordset. The contents of the array are output to the console.

The GetRows() method mimics the functionality of the GetRows() method of the ADO Recordset. First, an object array is created to hold the rows and columns in the table. The number of columns in the array is set to hold either all of the columns in the table or the subset of columns defined by the optional string array of column names. The number of rows in the table is set to hold either all of the rows in the table or the subset defined by the optional start row and row count arguments. The method then iterates over the collection of rows and columns in the table and sets the values in the array to the field values.

The C# code in Program.cs in the project ConvertQueryResultsArray is shown in Example 6-14.

Example 6-14. File: Program.cs for ConvertQueryResultsArray solution

using System; using System.Data; using System.Data.SqlClient; using System.Text; namespace ConvertQueryResultsArray { class Program ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.