如何用Linq聚合小数

时间:2012-02-13 16:47:38

标签: c# linq

我试着

Collection.Aggregate(0.0,(current, next) => current += next.decimalValue);

但是我得到将十进制转换为双倍的错误

另一个问题:对于“Sum”Linq,种子是默认的类型值? 意思是种子= 0表示小数...

4 个答案:

答案 0 :(得分:6)

编译器将0.0解释为double,您需要将类型指定为小数。请尝试以下方法:

Collection.Aggregate(0m, (current, next) => current += next.decimalValue);

The m suffix表示数字真实文字(在本例中为0)是小数。

答案 1 :(得分:2)

您是否尝试过0.0M

Collection.Aggregate(0.0M,(current, next) => current += next.decimalValue);

答案 2 :(得分:1)

0.0是必须明确创建小数的双倍:

Collection.Aggregate(new decimal(0.0), (current, next) => current += next.decimalValue);

答案 3 :(得分:0)

您不需要0.0m,0m可以声明小数。下面是一段工作代码。

     var itemSums = pCurrentList.Aggregate((TotalSealedUnits: 0m, TotalSealedUnitSqFt : 0m, TotalLinInches: 0m, TotalOrders: 0m  ), 
        (Results, current) => (Results.TotalSealedUnits += current.TotalSealedUnits, Results.TotalSealedUnitSqFt += current.TotalSUSqFt, Results.TotalLinInches += current.TotalLInches, Results.TotalOrders += 1));


    txtTotalOrders.Text = itemSums.TotalOrders.ToString();
    txtTotalLinInches.Text = itemSums.TotalLinInches.ToString();
    txttotalSU.Text = itemSums.TotalSealedUnits.ToString();
    txtTotalSUSqFt.Text = itemSums.TotalSealedUnitSqFt.ToString();