CiccioMiami
CiccioMiami

Reputation: 8256

Check values inside a LINQ Sum() method with lambdas in C#

I have to sum all the values in one object. The values are retrieved from a database and stored in a List<T>. If one of the value is equal to -1 I want to use 0 in the sum instead.

Here is the code that I use to perform the task:

lprod_projectionActualvalue = lprod_monthlyReport.Sum(m => new
{
    Monthly_ActualValue = (m.Monthly_ActualValue != -1) ? 
      m.Monthly_ActualValue : 0F
});

Monthly_ActualValue is of type float?. The compiler gives me an error stating that I cannot convert anonymous type to float?. That is quite strange because I use the same code in the Select clause without getting any error. What could be the problem?

Thanks

Francesco

Upvotes: 2

Views: 1887

Answers (4)

Dan Tao
Dan Tao

Reputation: 128317

Your lambda does not return a float. It declares a new anonymous type with a single float property, Monthly_ActualValue. You cannot Sum objects of this type because addition is not defined for it.

Try this instead:

lprod_projectionActualvalue = lprod_monthlyReport.Sum(m =>
    (m.Monthly_ActualValue != -1) ? m.Monthly_ActualValue : 0F
);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499950

The problem is that you're creating an anonymous type using new { ... } for no particularly obvious reason... and Sum doesn't know how to add up values of the anonymous type Try this instead:

lprod_projectionActualvalue = lprod_monthlyReport
    .Sum(m => m.Monthly_ActualValue != -1 ? m.Monthly_ActualValue : 0F);

I'm slightly surprised by using a nullable type and a magic "doesn't count" value (-1). Normally you only need one of those options - but I'll take your word for it that this is really what you want :)

(I would suggest you look at the .NET naming conventions too... those underscores aren't conventional, and it's unclear to me what lprod means. Just general advice.)

Upvotes: 4

KeithS
KeithS

Reputation: 71565

You're creating a new anonymous type using the new {} keyword and brackets, which is never going to be convertible to a float. If you want the sum to be of a float, remove the anonymous type declaration and just specify the expression producing the float, like so:

lprod_projectionActualvalue = lprod_monthlyReport.Sum(m => (m.Monthly_ActualValue != -1) ? m.Monthly_ActualValue : 0F);

Upvotes: 7

Aducci
Aducci

Reputation: 26634

I would try adding a select first, then call the Sum method

lprod_projectionActualvalue = lprod_monthlyReport.Select(m => new
{
    Monthly_ActualValue = (m.Monthly_ActualValue != -1) ? m.Monthly_ActualValue : 0F
}).Sum(m => m.Monthly_ActualValue);

Upvotes: 1

Related Questions