Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal.TryParse in LINQ query - How to use the out parameter and avoid second conversion

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?

like image 485
webworm Avatar asked Dec 13 '25 04:12

webworm


2 Answers

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);
like image 197
Jonathon Chase Avatar answered Dec 15 '25 17:12

Jonathon Chase


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.

like image 36
user1574775 Avatar answered Dec 15 '25 17:12

user1574775