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());
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.
It will return an empty enumerable. It won't be null.
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.
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.
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;
})
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