Question

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; }    
}
Was it helpful?

Solution

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);
}

OTHER TIPS

One option is to follow the instructions in this MSDN article: How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow.

It's very straightforward:

  1. Copy the ObjectShredder<T> source code in the article and place it in its own file since it's a class. It's a lot of code, but it'll save you from manually needing to construct the DataTable.
  2. Add the CustomLINQtoDataSetMethods class from the article, which wraps the ObjectShredder in a nice extension method named CopyToDataTable.
  3. Next, use CopyToDataTable over an IEnumerable<T>.

With all those items in place, you'll be able to use it as follows:

DataTable table = cl.CopyToDataTable();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top