Divide by Zero Exception inside of a Linq Join Condition

lesponce 176 Reputation points
2022-09-07T15:33:00.93+00:00

Give the example below, I'm getting a Divide by Zero exception error. Can you please advise me how to set the Result value to zero if the data in field test1 is zero?
I can't use at "try catch" of "if statement" because the code that is doing the calculation is inside of a linq join condition. Thanks for your help.

            decimal? Result = 0;  
            decimal? test1 = 0;  
            decimal? test2 = 57;  
  
   
           Result = (decimal)(test1 == null ? 0 : ((test2 - (test1 ?? 0)) / test1));  
  
Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,766 Reputation points Volunteer Moderator
    2022-09-07T15:58:57.113+00:00

    simple:

    Result = (decimal)((test1 == null || test1 == 0) ? 0 : ((test2 - (test1 ?? 0)) / test1));

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. lesponce 176 Reputation points
    2022-09-07T16:29:48.553+00:00

    Hi Bruce, thanks for your response. If test2 is null, I get this error: Nullable object must have a value.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.