Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

(See the MSDN documentation for more information.)

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top