Linq to entities: round the sum
I need to round the sum of decimal?. I do:
group => new {
rounded_sum = gro开发者_Python百科up.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?
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 )
});
精彩评论