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));  
  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,233 questions
0 comments No comments
{count} votes

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.