如何检查以下代码以捕获除以零错误?
active = (g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
我想要这样的事情:
if(g.Sum(x => x.kullanim_T0) == 0)
{
return 1;
}
else
{
return g.Sum(x => x.kullanim_T0);
}
我可以在上面的linq代码行(if-else
)中写g.Sum(x => x.kullanim_T0)
吗?怎么样?
感谢。
答案 0 :(得分:5)
active = (g.Sum(x => x.kullanim_T0) == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / g.Sum(x => x.kullanim_T0)) * 100
但效率更高:
var kSum = g.Sum(x => x.kullanim_T0);
active = (kSum == 0 ? 1 : g.Sum(x => x.Kullanim_Reaktif) / kSum ) * 100