Reputation: 36733
I'm getting the following error when trying to get the sum in this Linq query:
InvalidCastException was unhandled. Specified cast is not valid.
I used the DataType property to triple check is that column is in fact a Double, and it is.
foreach (DataColumn item in _dttMasterViewTransaction.Columns)
{
if (item.ColumnName == "Dr")
{
//Outputs: System.Double!
MessageBox.Show(item.DataType.ToString());
}
}
var datos = _dttMasterViewTransaction.AsEnumerable().Where(r => (int)r["Entity"] == FundsID).Select(r => new EntityJESummary()
{
JEId = (int)r["JE ID"],
JEGroupingId = (int)r["JE Group"],
PartnershipId = (int)r["Entity"],
BookingDate = Convert.ToDateTime(r["GL Date"]),
EffectiveDate = Convert.ToDateTime(r["Effective Date"]),
Allocated = Convert.ToBoolean(r["Allocated"]),
JEEstate = (int)r["JE State"],
JEComments = r["JE Comments"].ToString(),
Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["Dr"]),
Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (double)s["CR"])
}).First();
Any suggestions on why this could occur?
Upvotes: 0
Views: 3400
Reputation: 12203
You may want to use Nullable form of Sum.
Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] ==
FundsID).Sum(s => (double?)s["Dr"]),
Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] ==
FundsID).Sum(s => (double?)s["CR"])
Check this link for more details:
Upvotes: 0
Reputation: 17631
If the values can be either null or an empty string, try this:
Debit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (String.IsNullOrEmpty(s["Dr"]) ? 0d : (double)s["Dr"])),
Credit = _dttMasterViewTransaction.AsEnumerable().Where(s => (int)r["Entity"] == FundsID).Sum(s => (String.IsNullOrEmpty(s["CR"]) ? 0d : (double)s["CR"]))
Upvotes: 0
Reputation: 25116
Are any of the entries null for that field? or are there some that are not doubles?
we'd need to see more data to get a better answer...
Upvotes: 1