c# - 将 LINQ 的输出转换为 Int16

标签 c# .net linq

我有以下 LINQ 表达式:

var ageEntry = from entry in args
                           where (entry.Key == "Age")
                           select entry.Value;

//I want age as Int16:
Int16 age = Convert.ToInt16(ageEntry); 

但是我得到以下异常:

Unable to cast object of type 'WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.String,System.String],System.String]' to type 'System.IConvertible'.

这不是我见过的最明显的异常,有人可以向我解释一下吗?

最佳答案

首先,ageEntry是一个序列,是查询的结果。看起来您希望您的查询只有一个结果。因此,你可以说:

short age = Convert.ToInt16(ageEntry.Single());

which isn't the clearest exception I've seen, can someone please explain this to me?

其实很清楚。它告诉你 ageEntry 的类型是WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.String,System.String],System.String]而且它无法转换它。这是你的主要线索 ageEntry不代表数字或可以转换为您认为应该的数字的东西。

相反,它代表一个查询,该查询过滤并投影特定序列(在您的例子中为 args )。基本上,ageEntry知道如何过滤 KeyValuePair<string, string> 的序列并转换到string .这就是为什么你必须使用 Enumerable.Single .您是说“给我一个查询结果,该查询是通过执行您知道如何执行的所有过滤和投影得出的(顺便说一句,如果没有单个结果,则抛出异常)。”

关于c# - 将 LINQ 的输出转换为 Int16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7462642/

相关文章:

c# - Emgu CV - 将灰度图像组合成单个 Bgr 图像

c# - Newtonsoft.Json - 忽略 DataContractAttribute

c# - 测试环境中的 DataService 在获取 InMemoryDb 数据时总是返回 null

c# - 查找我的可执行文件所在文件夹的首选方法是什么?

c# - 如何使用 LINQ to Entities(带转换)返回嵌套数据集?

c# - 密码字段的水印文本

c# - 重新排序数据表列

c# - 在 ASP.NET MVC 中从 ModelMetadataProvider 获取包含对象实例

c# - 如何设置基于参数值动态返回结果的模拟?

c# - 如何使用 LINQ 从 DataTable 中删除行?