2

I need to round the sum of decimal?. I do:

group => new {
rounded_sum = group.Sum(f => f.A) == null ? null : (decimal?)Decimal.Round((decimal)group.Sum(f => f.A), 0),
}

which isn't very nice. Perhaps there is a cleaner way?

ren
  • 3,843
  • 9
  • 50
  • 95

1 Answers1

5

Could you use the null coalescing operator? I realize that it doesn't do exactly the same thing, but it might be appropriate.

group => new {
   rounded_sum = Decimal.Round( group.Sum( f => f.A ) ?? 0M, 0 )
}

Another alternative would be to do the operation in two steps, which would save running the sum operation twice, though it's even "wordier."

  ...
   group => new {
       sum = group.Sum( f => f.A )
})
.Select( g => new {
  rounded_sum = sum == null ? null : (decimal?)Decimal.Round( sum.Value, 0 )
});
tvanfosson
  • 524,688
  • 99
  • 697
  • 795