Search code examples
c#vb.netvisual-studio-lightswitch

How do I make an "IF" statement in a computed property of an Entity in Lightswitch C#?


I am trying to calculate the % of the poverty level give income, number of people in a household, and the federal guidelines. The code that I use in Access with the expression builder (VB I believe) is:

IIf([NumberInHousehold]>=1,([AnnualHouseHoldIncome]/(7880+([NumberInHousehold]*4180))),0)

Is there a c# equivalent? The NumberInHouseHold has a datatype of "integer" and the datatype for AnnualHouseHoldIncome is "Money". The field to be computed is also "integer".


Solution

  • The most direct equivalent to the VBA (and VB.Net) IIf() function is the "?: " operator (typically known as the "ternary" or "conditional" operator), e.g.:

    result = numberInHousehold >= 1
        ? (annualHouseholdIncome / (7880 + (numberInHousehold * 4180)))
        : 0;
    

    Note that the ternary operator will only evaluate the result branch that it uses, whereas IIf() is a function that evaluates all of its arguments regardless of the truth of the condition. Most of the time, the ternary operator's behavior is what you want, but it is different from IIf().