我有以下 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 'WhereSelectEnumerableIterator
2[System.Collections.Generic.KeyValuePair
2[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/