I have two data tables and would like to join the two tables to find the difference between the two columns, however it keeps returning null and erroring out at CopyToDataTable method as you cannot pass null into it. I have checked just before this code that there are exactly same data in TestOutput and ExpectedOutput tables.
Here’s my code:
IEnumerable<DataRow> diff =
(from datarows1 in TestOutput.AsEnumerable()
join datarows2 in ExpectedOutput.AsEnumerable()
on datarows1.Field<String>("external_id") equals datarows2.Field<String>("external_id")
select new
{
KeyId = datarows1.Field<String>("external_id"),
Difference = datarows1.Field<Decimal>("quantity") - datarows2.Field<Decimal>("quantity")
}) as IEnumerable<DataRow>;
DataTable difference = diff.CopyToDataTable<DataRow>();
Error Message @ last row:
ArgumentNullException was unhandled – value cannot be null. Parameter name:source
The problem is the
as IEnumerable<DataRow>cast. If you remove that line you will see that your query is selecting out an anonymous type with propertiesKeyIDandDifference, not an IEnumerable. Theasoperator attempts to castIEnumerable<DataRow>and returns anullif no such cast is possible. That is where your null reference exception is coming from.To fix this, you need to find a different technique of populating the DataTable from your
IEnumerable<a'>(wherea'is the anonymous type)