I’m trying to extract some data from XML using Linq to XML, and I have the following code:
commisionPct = XDocument.Parse(commissionXml)
.Descendants("Range")
.Attributes("commission")
.Select(x => Convert.ToDecimal(x.Value))
.FirstOrDefault();
The problem is I do not want it to exception if x.Value is not a decimal. Normally I’d use decimal.TryParse but I am not sure of a clean way to do this inside of a linq statement. I guess I could surround this with a try/catch block but I was curious if there was a better way to do this inside of Linq.
I would prefer it to return the decimal default value (0) if it’s not a decimal.
Change your
Selectlike this:Or, create a method to handle it for you.