Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

xml

linq

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());
like image 659
Daedalus Avatar asked Nov 12 '18 09:11

Daedalus


People also ask

How do you use take and skip in LINQ?

The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

What does LINQ return when the results are empty?

It will return an empty enumerable. It won't be null.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Is LINQ inefficient?

It is slightly slowerLINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.


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;
         })
like image 54
Ric Avatar answered Oct 25 '22 02:10

Ric