c# – Linq哪里有三元和括号
发布时间:2020-12-15 23:23:52 所属栏目:百科 来源:网络整理
导读:我有以下查询: return Postcodes .Where( s = s.Postcode.IndexOf(term,StringComparison.InvariantCultureIgnoreCase) -1 string.IsNullOrEmpty(country) ? true : s.CountryRegionID.Equals(country,StringComparison.InvariantCultureIgnoreCase) ) .Sel
我有以下查询:
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(); 现在我希望这会返回所有匹配国家和术语的邮政编码,但由于某种原因,它只匹配该术语,如果该国家为空,然后如果该国家不为空,则忽略该术语并且仅匹配该国家. 如果我在三元组周围放置括号: 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(); 然后它完全按照我的预期工作.为什么额外的括号对有所不同,因为代码分析总是抱怨我把括号括在三元组周围? 解决方法
在C#中,三元运算符的优先级低于条件AND运算符.因此,没有括号并在三元运算符之前进行评估,并且您有三元运算符来检查邮政编码和国家/地区.即默认情况下
( checkPostcode && countryNotNull) ? true : checkCountry 添加括号时,拆分三元运算符,从邮政编码检查中检查国家/地区 checkPostcode && (countryNotNull ? true : checkCountry) 见7.2.1 Operator precedence and associativity (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |