How do I ignore/remove non-number values from linq query results C#

Viewed 197

I have a linq query which iterates over hundreds of XML elements to count the quantity of specific tools used in a collection of tools.

However, the qty element in the tools xelement collection, which should contain a number, occasionally contains text such as "As required" as opposed to a specific number. This clearly causes problems.

Is there a simple additional step i can put into this linq query (i'm not good with linq) that will either ignore non-number values, or filter them out?

Linq query is:

Dictionary<int, int> dict = listTools.Descendants("tool")
                .GroupBy(x => (int)x.Element("id"), y => (int)y.Element("qty"))
                .ToDictionary(x => x.Key, y => y.Sum());
1 Answers

Use int.TryParse:

.GroupBy(x => (int)x.Element("id"), 
         y => int.TryParse(y.Element("qty"), out int qty) ? qty : 0)

From the docs:

The conversion fails if the s parameter is null or Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue

Try this:

.GroupBy(x => (int)x.Element("id"), 
         y => 
         {
             int qty = 0;
             if (int.TryParse(y.Element("qty"), out qty))
                 return qty;
             return 0;
         })
Related