views:

2006

answers:

3

I'd like to create a data table given a List using the CopyToDataTable method available in DataTableExtensions. I've previously asked the question How do I transform a List into a DataSet? and got an exceptional answer from CMS which was to achieve what I wanted by creating an extension public static DataTable ToDataTable<T>(this IEnumerable<T> collection)

I've been using what he suggested...but recently I've seen in a blog that there already exists such an extension... CopyToDataTable<T>(this IEnumerable<T> source) : DataTable which exists in System.Data.DataTableExtensions.

As a result, I figure I should switch over to using this inbuilt extension method instead of using one that I'd have to maintain myself.

Unfortunately, I'm having a bit of trouble figuring out how to use it.

I can take my IList and say myListofMyClass.CopyToDataTable() but I get a compile error that says "The type 'MyClass' must be convertible to 'System.Data.DataRow' in order to use it as parameter 'T' in the generic method..."

Is there something special I need to do MyClass in order to make it convertible to System.Data.DataRow? Is there some interface I need to implement?

A: 

Alas, for CopyToDataTable, T must be DataRow (or a type derived from DataRow).

(See the MSDN documentation for more information.)

Jeff Sternal
*sigh* I was hoping that wasn't the case. I had read that MSDN doc but didn't quite catch on to the fact that it absolutely had to be a DataRow or something deriving from DataRow...
mezoid
+1  A: 

This isn't really what you want. CopyToDataTable is made for copying collections specifically of DataRows into a DataTable (which is a collection of DataRows, plus a bunch of junk; CTDT handles the "junk" aspect.)

mquander
+1  A: 

See this link:

http://blogs.msdn.com/aconrad/archive/2007/09/07/science-project.aspx

Basically, it did used to be part of Linq, but for some reason it was removed. His method there does work great though, so check it out.

BFree
I've gone with this answer because its the closest to what I had wanted. I don't think I'll use this solutions...but at least it answers my question about why I couldn't use it since they dropped the feature and the blog post was from back in the beta days...
mezoid
Why won't you use this? We added it to our framework at work (along with the null fix you'll find in one of the comments on that blog post) and it really works great.
BFree