我有一个 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/