Reputation: 3612
I have the following data:
Number can be NULL
I am writing a LINQ statement to get the following number as a result:
Needed result: 290
My LINQ statement currently looks like this:
(from b in data
where b.Number.HasValue
select new
{
Number = b.Number.Value,
b.Factor
}).Sum(o => o.Number * (o.Factor / 100));
I get the following error:
The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
Upvotes: 2
Views: 5424
Reputation: 3612
This can be fixed by casting the contents of the Sum like this:
(from b in data
where b.Number.HasValue
select new
{
Number = b.Number.Value,
b.Factor
}).Sum(o => (decimal?)(o.Number * ((decimal)o.Factor / 100))) ?? 0;
(note: I found the answer while writing the question and thought I might as well formulate an answer and publish it for anyone else to find)
Upvotes: 5