如何解决Linq可以在Regex替换之前检查值是否为Null
我正尝试替换下面的字符,以便仅对所有列表值进行排序。问题在于,有时buildpartyname为null,而Im却因为尝试对空值进行正则表达式替换而收到错误消息。
无论如何,在Linq语句中进行替换之前,是否有必要检查order by子句中的BuiltPartyName值是否为空?
string pattern = ".,"; //characters we dont want to be considered in the sorting of records.
string hyphenPattern = "-";
PartyListing = PartyListing.OrderBy(p => Regex.Replace(Regex.Replace(p.BuiltPartyName,pattern,""),hyphenPattern,"000000")).ToList(),
解决方法
尝试一下:
string pattern = ".,"; //characters we dont want to be considered in the sorting of records.
string hyphenPattern = "-";
PartyListing = PartyListing.Where(p => !string.IsNullOrWhiteSpace(p.BuiltPartyName)).OrderBy(p => Regex.Replace(Regex.Replace(p.BuiltPartyName,pattern,""),hyphenPattern,"000000")).ToList(),
之所以可行,是因为您在where子句中使用!= null,但是空字符串“”不为null,因此您需要检查null或空格。
或尝试以下操作:
string pattern = ".,"; //characters we dont want to be considered in the sorting of records.
string hyphenPattern = "-";
PartyListing = PartyListing.Where(p => p.BuiltPartyName !=null).OrderBy(p => string.IsNullOrWhiteSpace(p.BuiltPartyName) ? "" : Regex.Replace(Regex.Replace(p.BuiltPartyName,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。