【发布时间】:2019-02-21 20:48:20
【问题描述】:
我正在使用 LINQ to XML 查询来遍历 XML 文件并收集余额为正的那些节点。 XML 可能有一个空的余额节点或包含无法转换为十进制的内容,因此我进行了检查以跳过这些值。其中一项检查使用decimal.TryParse()查看余额节点的内容是否可以转换为十进制。如果可以转换,我有一个后续 Where 子句来执行转换。
XML 结构:
<Invoice>
...
<balance>Could be any string here or empty</balance>
...
</Invoice>
代码:
decimal convertedDecimalButUnused;
var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => !x.Element("balance").IsEmpty);
.Where(x => Decimal.TryParse(x.Element("balance").Value, out convertedDecimalButUnused))
.Where(x => Convert.ToDecimal(x.Element("balance").Value) > 0);
我的问题是我是否可以使用decimal.TryParse() 的out 参数而不是第二次执行十进制转换?
【问题讨论】:
标签: c# linq-to-xml tryparse