2011-10-11 114 views
2

我需要舍入小數的總和?我這樣做:Linq to entities:四捨五入

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

這不是很好。也許有更清晰的方法?

回答

5

你可以使用空合併運算符嗎?我意識到它並不完全一樣,但它可能是適當的。

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

另一種方法是做手術的兩個步驟,這將節省運行和操作兩次,但它甚至「wordier。」

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