在我的代码中,我通过迭代foreach
在DataRow
内的值中添加了一个列表。我的代码如下,
ActivityUserResult Result = new ActivityUserResult();
Result.TransacDetails = new List<TransactionStatistics>();
foreach (DataRow row in ds.Tables[2].Rows)
{
Result.TransacDetails.Add(new TransactionStatistics()
{
Id = Convert.ToString(row["Id"]),,
AssistCount = Convert.ToInt32(row["AssistCount"]),
WaitTime = Convert.ToInt32(row["WaitTime"]),
AverageStandardWaitTime = (Convert.ToInt32(row["WaitTime"]) / Convert.ToInt32(row["AssistCount"])) / 60
});
}
我需要通过将AverageStandardWaitTime
除以WaitTime
得到AssistCount
的值。为此,我在循环中添加了此
AverageStandardWaitTime = (Convert.ToInt32(row["WaitTime"]) / Convert.ToInt32(row["AssistCount"])) / 60
但有时AssistCount
的值将为零。所以我遇到了这个错误。
System.DivideByZeroException: 'Attempted to divide by zero.'
如何检查AssistCount
的值是否为零?如果不为零,则需要除法,否则需要避免除法,需要将AverageStandardWaitTime
的值设置为0
答案 0 :(得分:1)
您可以为此使用三元运算符,这很简单:
AverageStandardWaitTime = (Convert.ToInt32(row["AssistCount"]) > 0
? Convert.ToInt32(row["WaitTime"]) / Convert.ToInt32(row["AssistCount"])
: 0)
如果愿意,可以重新使用转换后的值,而不是每次都转换该值。
foreach (DataRow row in ds.Tables[2].Rows)
{
Result.TransacDetails.Add(new TransactionStatistics()
{
Id = Convert.ToString(row["Id"]),,
AssistCount = Convert.ToInt32(row["AssistCount"]),
WaitTime = Convert.ToInt32(row["WaitTime"]),
AverageStandardWaitTime = (Convert.ToInt32(row["WaitTime"]) > 0
? (Convert.ToInt32(row["WaitTime"]/Convert.ToInt32(row["AssistCount"]))/60
: Convert.ToInt32(row["WaitTime"])
)
});
}
答案 1 :(得分:1)
您可以创建函数,然后对其进行调用,这样您就可以获得清晰的代码和有关某些数据错误的正确消息
public double CalculateAverageStandardWaitTime(DataRow row)
{
int waitTime = Convert.ToInt32(row["WaitTime"];
int assistcount = Convert.ToInt32(row["AssistCount"]);
if(assistcount != 0 ) {
return (Convert.ToInt32(row["WaitTime"]) /
Convert.ToInt32(row["AssistCount"])) / 60;
}
else {
//log message that value is less then zeor
//return some defautl value
return -1; //0
}
}
您的代码将是
Result.TransacDetails.Add(new TransactionStatistics()
{
Id = Convert.ToString(row["Id"]),,
AssistCount = Convert.ToInt32(row["AssistCount"]),
WaitTime = Convert.ToInt32(row["WaitTime"]),
AverageStandardWaitTime = CalculateAverageStandardWaitTime(row)
});