2

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.

Matthew Verstraete
  • 6,335
  • 22
  • 67
  • 123

2 Answers2

3

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.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thank you, you are right in my intent and I will look at EPPLus. I will also look into the link to examine it more just as a learning thing. – Matthew Verstraete Feb 06 '17 at 16:32
  • MoreLINQ is open source. You can find the source for ToDataTable [here](https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/ToDataTable.cs) – Panagiotis Kanavos Feb 06 '17 at 16:33
0
public DataTable TableFromMyViewModel(params MyViewModel[] items)
{
    DataTable _result = new DataTable("MyViewModel");

    // Do this for each field
    _result.Columns.Add("Field1", typeof(String));
    _result.Columns.Add("Field2", typeof(int));
    _result.Columns.Add("Field3", typeof(String));

    foreach (MyViewModel _item in items)
    {
        DataRow _row = _result.NewRow();
        _row["Field1"] = _item.Field1;
        _row["Field2"] = _item.Field2;
        _row["Field3"] = _item.Field3;
        _result.Rows.Add(_row);
    }

    return _result;
}
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37