views:

450

answers:

4

Is there any way (through a extention mechanism?) to get the Sum() function to allways return 0.

My workaround now is to write like this, but I'm hoping there's a better solution?

((int?)e.CampaignCodes.Sum(f => f.Enquiries.Count()) ?? 0),
+2  A: 

That's a pretty good way actually. I think the better question is why is it null to begin with? Unless the entity you're invoking the sum on is null, the query should always return 0. It might be a better solution to see whether your entity is valid at the start as opposed to forcing the sum to always return 0 -- Null means there's a problem.

MunkiPhD
+1  A: 

The question whether it should be 0 or null is a thorny one. It depends on what you interpret "sum" to be. If it is "the sum of all (selected) records", null would be appropriate when any of the records contain a NULL, since you technically don't know for sure. If it means "the sum of all known (selected) records", it should return 0.

Which one is appropriate in your situation is something only you can decide, so I think what you did here is not a bad solution at all.

For more information on the thornyness of NULL read some of Chris Date's and Hugh Darwen's writings on the subject.

Rik
You're right. The problem of returing 0 is that this would require any summable object to have a neutral element which is strange because I can write a + b without having one.
Dario
+6  A: 

Your workaround there is a good one. Why don't you write an extension method for IEnumerable similar to Sum called something like SumOrDefault. Then you could just reuse your extension method and you will not have to see the workaround.

Your extension method will be very simple and just use the exact code from your workaround.

Brendan Enrick
+1  A: 

Write an extension method:

public static Decimal? CorrectSum<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal?> selector)
{

Decimal? sum = null;
foreach (TSource s in source)
{
    Decimal? val = selector(s);

    if (val.HasValue == true)
    {
        sum = (sum ?? 0) + val;
    }
}

return sum;

}

Dhawal