Linq where with triple and brace

I have the following request:

return Postcodes
            .Where(
                s => s.Postcode.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) > -1 &&
                string.IsNullOrEmpty(country) ? true : s.CountryRegionID.Equals(country, StringComparison.InvariantCultureIgnoreCase)
            )
            .Select(p => new { label = p.Postcode, value = p.RecID })
            .ToList();

      

Now I was expecting this to return all postcodes matching both the country and the term, but for some reason it only matches the member if the country is zero, and then if the country is not zero it ignores that term and just corresponding country.

If I put parentheses around the ternary:

return Postcodes
            .Where(
                s => s.Postcode.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) > -1 &&
                (string.IsNullOrEmpty(country) ? true : s.CountryRegionID.Equals(country, StringComparison.InvariantCultureIgnoreCase))
            )
            .Select(p => new { label = p.Postcode, value = p.RecID })
            .ToList();

      

Then it works exactly as I expected. Why does the extra pair of parentheses matter since code analysis always complains about putting parentheses around tees?

+3


source to share


1 answer


In C #, the ternary operator has a lower precedence than the conditional AND operator, so no parentheses AND is evaluated before the ternary operator and you have a ternary operator that checks the postal code AND the country. That is, by default

( checkPostcode && countryNotNull) ? true : checkCountry

      

When you add parentheses, you split the ternary operator which checks the country to check the postal code



checkPostcode && (countryNotNull ? true : checkCountry)

      

See 7.2.1 Operator Precedence and Associativity

+7


source







All Articles