Looking at your screen-shot, the
CurrentMeterReading
field is an integer in one table, and a floating-point number in another.
The
Field<T>
extension method does not attempt to change the type of the source field. It simply tries to unbox it to the requested type. If the source type doesn't precisely match the requested type, it will fail with an
InvalidCastException
.
NB: The code you have which initializes the columns of the
DataTable
is not necessary. The tables you create are then immediately thrown away and replaced with the tables loaded from the database and Excel file.
You will need to debug your code to work out what the actual field types are. Alternatively, use
Convert.ToDecimal
to try to change the type:
where Convert.ToDecimal(y["CurrentMeterReading"] > Convert.ToDecimal(x["CurrentMeterReading"])
select new { UnitCode = x.Field<int>("UnitCode"), CurrentReading = Convert.ToDecimal(x["CurrentMeterReading"]) })