Science Project

Science Project

In the original Linq CTP and the first Orcas Beta, we included a DataSet specific Linq operator called CopyToDataTable<T> (It was called ToDataTable at one point also). For Beta 2 of Orcas, we ended up restricting this method to only work with DataRows (or some derived type) via a generic constraint on the method.

The reason for this was simply resource constraints. When we started to design how the real version of CopyToDataTable<T> should work, we realized that there are a number of potentially interesting mappings between objects and DataRows and didn't have the resources to come up with a complete solution. Hence, we decided to cut the feature and release the source as a sample.

Surprising to us, a lot of folks noticed this and were wondering where the feature had gone. It does make a nice solution for dealing with projections in Linq in that one can load instances of anonymous types into DataRows.

So as promised, below is sample code of how to implement CopyToDataTable<T> when the generic type T is not a DataRow.

A few notes about this code:

1. The initial schema of the DataTable is based on schema of the type T. All public property and fields are turned into DataColumns.

2. If the source sequence contains a sub-type of T, the table is automatically expanded for any addition public properties or fields.

3. If you want to provide a existing table, that is fine as long as the schema is consistent with the schema of the type T.