在LINQ groupby select语句中防止被0除
我有以下LINQ声明:在LINQ groupby select语句中防止被0除,linq,Linq,我有以下LINQ声明: var result = CommisionDataContext.COMMISSIONS .Where(c.PRODUCT == 'Computer') .GroupBy(g => new { CostCenter = g.COST_CENTER, Product = g.PRODUCT, } .Select(group => new {
var result = CommisionDataContext.COMMISSIONS
.Where(c.PRODUCT == 'Computer')
.GroupBy(g => new
{
CostCenter = g.COST_CENTER,
Product = g.PRODUCT,
}
.Select(group => new
{
Revenue = group.Sum(p => p.REVENUE),
Volume = group.Sum(p => p.VOLUME),
Avg = group.Sum(p => p.REVENUE) / group.Sum(p => p.VOLUME),
});
我如何防止可能发生的被零除异常,如果是,我只希望平均值等于0。只要替换即可
Avg = group.Sum(p => p.REVENUE) / group.Sum(p => p.VOLUME),
与
为了避免求和过多,您应该能够执行如下操作:注意,您的代码不会编译:
...
.Select(group => new
{
Revenue = group.Sum(p => p.REVENUE),
Volume = group.Sum(p => p.VOLUME)
})
.Select(item => new
{
item.Revenue,
item.Volume,
Avg = item.Volume == 0 ? 0 : item.Revenue / item.Volume
});
要小心,因为C Double可以处理无穷大的值,事实上,如果您尝试的话
var x = 5.0 / 0.0
你会发现x=无穷大,毫无例外,这与0真的不同!因此,如果你想要你的平均值=0,请确保从数学和代表性的角度来看它是正确的。例如,我使用的是营销公式和图表,知道我的平均值是真的0还是近似值很重要,以避免错误的图表代表和误解
无论如何,此代码避免了被零除的异常。如果发现AVG操作的精确值有用,则需要将AVG设置为Double,如果卷和为0,则考虑无穷大返回值
Avg=Convert.ToDoublegroup.pulls=>p.REVENUE/group.pulls=>p.VOLUME
否则,您可以使用一次评估前检查方法
var x = Convert.ToDouble(group.Sum(p => p.REVENUE)) / group.Sum(p => p.VOLUME));
Avg = Double.IsInfinity(x)? 0 : x;
在计算之前存储group.pull=>p.VOLUME的值可能是一个好主意,以防止计算两次总和。@Joshua-好主意。如果使用查询语法,您可以使用let语句来实现,但我认为使用方法语法无法实现。
var x = Convert.ToDouble(group.Sum(p => p.REVENUE)) / group.Sum(p => p.VOLUME));
Avg = Double.IsInfinity(x)? 0 : x;