Search code examples
c#listdatarowdivide-by-zero

How to check values is zero inside DataRow


In my code, I'm adding a list to values inside the foreach by iterating DataRow. My code as follows,

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                    
    });
}

I need to get AverageStandardWaitTime value by dividing WaitTime by AssistCount. To do that I added this inside loop

AverageStandardWaitTime = (Convert.ToInt32(row["WaitTime"]) / Convert.ToInt32(row["AssistCount"])) / 60  

But sometimes AssistCount value will be Zero. So I'm getting this error.

System.DivideByZeroException: 'Attempted to divide by zero.' 

How can I check if AssistCount value is Zero? if not zero I need to divide and otherwise I need to avoid the dividing and need to set AverageStandardWaitTime value as 0


Solution

  • You can use ternary operator for this which is pretty straightforward:

    AverageStandardWaitTime = (Convert.ToInt32(row["AssistCount"]) > 0 
                                ? Convert.ToInt32(row["WaitTime"]) / Convert.ToInt32(row["AssistCount"]) 
                                : 0)
    

    you can make it better by reusing the converted values if want to instead of converting the value every time.

    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"])
                                      )                   
        });
    }