I am trying to take a Linq query and populate a datatable. After a day of trying various methods I have something that will compile but my issue is that the CopyToDataTable is giving a null exception.
IEnumerable<DataRow> cancellations = cl.AsEnumerable() as IEnumerable<DataRow>;
Trace.WriteLine(cancellations);
DataTable datatable = cancellations.CopyToDataTable<DataRow>();
In Intellitrace, if I hover over cancellations it states Null and the Trace confirms that, over cl it has one record as expected as well as one record if I look at the entry of the method.
Am I missing something simple having stared at it all day?
public class CancellationList
{
public int SchemeId { get; set; }
public DateTime EffectiveDate { get; set; }
public DateTime TransactionDate { get; set; }
public DateTime ExpiryDate { get; set; }
}
There isn't going to be a built in way to do this. You will need to code it. If you just want it to work with CancellationList you can do this
var cl = new List<CancellationList>();
var dataTable = new DataTable();
var toObject = cl.Select(c => new object[] {c.SchemeId, c.EffectiveDate, c.TransactionDate, c.ExpiryDate});
dataTable.Columns.Add("SchemeId", typeof (int));
dataTable.Columns.Add("EffectiveDate", typeof (DateTime));
dataTable.Columns.Add("TransactionDate", typeof(DateTime));
dataTable.Columns.Add("ExpiryDate", typeof(DateTime));
foreach (var data in toObject)
{
dataTable.Rows.Add(data);
}