LINQ查询中的Decimal.TryParse - 如何使用out参数并避免第二次转换

问题描述 投票:3回答:3

我正在使用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);

我的问题是,如果我可以使用outdecimal.TryParse()参数而不是第二次执行十进制转换?

c# linq-to-xml tryparse
3个回答
3
投票

只需根据TryParse进行比较。您可以利用C#7功能,允许您在线声明值。

例如:

var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => !x.Element("balance").IsEmpty);
.Where(x => Decimal.TryParse(x.Element("balance").Value, out var val) && val > 0)

由于TryParse将处理元素是否为空,您也可以放弃检查。最后,您可以通过以下方式获得所需的结果:

var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => decimal.TryParse(x.Element("balance").Value, out var val) && val > 0);

1
投票

是的你可以这样做:

decimal convertedDecimalButUnused;
var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => !x.Element("balance").IsEmpty);
.Where(x => Decimal.TryParse(x.Element("balance").Value, out convertedDecimalButUnused) && convertedDecimalButUnused > 0);

您可以使用等于AND的&&在Where函数内链接多个断言。


1
投票

尝试编写一个将XElement转换为Decimal的实用程序扩展方法。在这种情况下,您可以将非十进制值视为零,因为您只对正值感兴趣。如果要区分实际0值和非小数值,则该方法可以返回可为空的小数。

public static class UtilityExtensions {
    // return decimal? to differentiate between real zero and non-decimal values
    public static decimal ToDecimal(this XElement element){
        if(element == null || element.IsEmpty) return 0; // return null for decimal?
        decimal value;
        // if you can use C# 7, code can be more succinct with inline declaration
        return Decimal.TryParse(element.Value, out value) ? value : 0; // return null instead of 0 for decimal?
    }
}

现在你的LINQ更简单了。这也将处理缺少“balance”元素本身的情况。

var resultsWithPositiveBalance = xml.Descendants("Invoice")
         .Where(x => !x.Element("balance").ToDecimal() > 0);

如果你最终使用decimal?版本:

var resultsWithPositiveBalance = xml.Descendants("Invoice")
         .Where(x => (!x.Element("balance").ToDecimal() ?? 0 ) > 0);
© www.soinside.com 2019 - 2024. All rights reserved.