如何忽略/删除linq查询结果C#中的非数值

Dae*_*lus 7 .net c# xml linq

我有一个linq查询,它迭代了数百个XML元素来计算工具集合中使用的特定工具的数量.

但是,工具xelement集合中的qty元素应该包含一个数字,偶尔会包含诸如"As required"之类的文本,而不是特定的数字.这显然会导致问题.

是否有一个简单的附加步骤,我可以放入这个linq查询(我对linq不好),它会忽略非数字值,还是过滤掉它们?

Linq查询是:

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());
Run Code Online (Sandbox Code Playgroud)

Ric*_*Ric 7

用途int.TryParse:

.GroupBy(x => (int)x.Element("id"), 
         y => int.TryParse(y.Element("qty"), out int qty) ? qty : 0)
Run Code Online (Sandbox Code Playgroud)

来自文档:

如果s参数为null或Empty,格式不正确,或者表示小于MinValue或大于MaxValue的数字,则转换失败

试试这个:

.GroupBy(x => (int)x.Element("id"), 
         y => 
         {
             int qty = 0;
             if (int.TryParse(y.Element("qty"), out qty))
                 return qty;
             return 0;
         })
Run Code Online (Sandbox Code Playgroud)