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

mezoid picture mezoid · Feb 25, 2009 · Viewed 10k times · Source

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?

Answer

BFree picture BFree · Feb 25, 2009

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.