Matthew Matthew - 4 years ago 70
C# Question

Easy way to fill a DataTable from a List<Model>?

I am calling into a method that returns a

List<MyViewModel>
and want to fill a
DataTable
from that. I can not change the return type as this method is called in a few others places that need it in that list form. I know I could iterate though the list and fill the table in one row at a time but I was hoping there was more elegant solution like it's
.Load
function for
iDataReader
.

Answer Source

From the comments it seems the real problem is that you want to export a strongly typed list to an Excel file but the library you use only accepts a DataTable.

I'd suggest you use the EPPlus library instead, which can load data both from a DataTable and collections, eg:

sheet.LoadFromDataTable(myTable);

or

sheet.LoadFromCollection(myList);

EPPlus is available as a NuGet package too.

In general, you can easily convert a collection to a DataTable with MoreLINQ's ToDataTable() extension, eg:

var myTable=myList.ToDataTable();

You can find the extension's code here. MoreLINQ is available as a NuGet package as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download