I am using a LINQ to XML query to go through a XML file and collect those nodes where the balance is positive. The XML may have an empty balance node or contain content that cannot be converted to decimal so I have checks in place to skip such values. One of the checks used decimal.TryParse() to see if the content of the balance node can be converted to decimal. If it can be converted I have a followup Where clause that performs the conversion.
XML structure:
<Invoice>
...
<balance>Could be any string here or empty</balance>
...
</Invoice>
Code:
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);
My question is if I can make use of the out parameter of the decimal.TryParse() instead of performing the decimal conversion a second time?
Just do the comparison in line with the TryParse. You can take advantage of the C#7 feature allowing you to declare the value in line.
For example:
var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => !x.Element("balance").IsEmpty);
.Where(x => Decimal.TryParse(x.Element("balance").Value, out var val) && val > 0)
Since TryParse will handle if the element is empty for you already, you can forgo checking that as well. In the end, you can get the result you want with this:
var resultsWithPositiveBalance = xml.Descendants("Invoice")
.Where(x => decimal.TryParse(x.Element("balance").Value, out var val) && val > 0);
Yes you can do this:
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);
You can chain multiple assertions together inside the Where function using && which equates to AND.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With