How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow

 

The DataTable object is often used for data binding. The CopyToDataTable method takes the results of a query and copies the data into a DataTable, which can then be used for data binding. The CopyToDataTable methods, however, only operate on an IEnumerable<T> source where the generic parameter T is of type DataRow. Although this is useful, it does not allow tables to be created from a sequence of scalar types, from queries that project anonymous types, or from queries that perform table joins.

This topic describes how to implement two custom CopyToDataTable<T> extension methods that accept a generic parameter T of a type other than DataRow. The logic to create a DataTable from an IEnumerable<T> source is contained in the ObjectShredder<T> class, which is then wrapped in two overloaded CopyToDataTable<T> extension methods. The Shred method of the ObjectShredder<T> class returns the filled DataTable and accepts three input parameters: an IEnumerable<T> source, a DataTable, and a LoadOption enumeration. The initial schema of the returned DataTable is based on the schema of the type T. If an existing table is provided as input, the schema must be consistent with the schema of the type T. Each public property and field of the type T is converted to a DataColumn in the returned table. If the source sequence contains a type derived from T, the returned table schema is expanded for any additional public properties or fields.

For examples of using the custom CopyToDataTable<T> methods, see Creating a DataTable From a Query.

To implement the custom CopyToDataTable<T> methods in your application

  1. Implement the ObjectShredder<T> class to create a DataTable from an IEnumerable<T> source:

    [!CODE [DP Custom CopyToDataTable Examples#ObjectShredderClass](../CodeSnippet/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples#objectshredderclass)]

  2. Implement the custom CopyToDataTable<T> extension methods in a class:

    [!CODE [DP Custom CopyToDataTable Examples#CustomCopyToDataTableMethods](../CodeSnippet/VS_Snippets_ADO.NET/DP Custom CopyToDataTable Examples#customcopytodatatablemethods)]

  3. Add the ObjectShredder<T> class and CopyToDataTable<T> extension methods to your application.

    Module Module1  
        Sub Main()  
        ' Your application code using CopyToDataTable<T>.  
        End Sub  
    End Module  
    
    Public Module CustomLINQtoDataSetMethods  
    …  
    End Module  
    
    Public Class ObjectShredder(Of T)  
    …  
    End Class  
    
    
  4. class Program  
    {  
            static void Main(string[] args)  
            {  
               // Your application code using CopyToDataTable<T>.  
            }  
    }  
    public static class CustomLINQtoDataSetMethods  
    {  
    …  
    }  
    public class ObjectShredder<T>  
    {  
    …  
    }  
    
    

Creating a DataTable From a Query
Programming Guide

Show: