Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use System.Data.DataTableExtensions' CopyToDataTable method?

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?

like image 736
mezoid Avatar asked Oct 14 '22 16:10

mezoid


2 Answers

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.

like image 130
BFree Avatar answered Oct 18 '22 15:10

BFree


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

(See the MSDN documentation for more information.)

like image 25
Jeff Sternal Avatar answered Oct 18 '22 13:10

Jeff Sternal