c# - 如何从 linq 查询结果中忽略/删除非数字值 C#

标签 c# .net xml linq

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

但是,tools xelement 集合中的 qty 元素本应包含一个数字,但偶尔会包含诸如“按要求”之类的文本,而不是特定的数字。这显然会导致问题。

是否可以在这个 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());

最佳答案

使用int.TryParse:

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

来自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

试试这个:

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

关于c# - 如何从 linq 查询结果中忽略/删除非数字值 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53258996/

相关文章:

javascript - 如何在 SAPUI5 的 Xml View 中编写无限行重复器

c# - 如何强制文本为特定宽度?

c# - 字符串数组存储时间

c# - 在c#中使用ftp下载文件

c# - 当必须在 C# 中不断重新绘制控件时,如何避免屏幕闪烁?

.net - 从 TFS 2015 构建代理运行时,VS .NET Core 项目的 DotNet CLI 构建失败

c# - .NET - 如何比较 2 个代码块之间的性能?

java - SAXParseException;源代码解析 : Cannot resolve the name '...' to a(n) 'type definition' component

c# - 在 MVC Controller 中加载 XML

c# - 如何在 EF 6.1 CodeFirst 中的 View 上添加导航属性