I’ve got the following LINQ expression:
var ageEntry = from entry in args
where (entry.Key == "Age")
select entry.Value;
//I want age as Int16:
Int16 age = Convert.ToInt16(ageEntry);
However I get the following exception:
Unable to cast object of type
‘WhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.String,System.String],System.String]’
to type ‘System.IConvertible’.
which isn’t the clearest exception I’ve seen, can someone please explain this to me?
First,
ageEntryis a sequence, being the result of a query. It looks like you expect your query to have a single result. Thus, you can say:Actually, it’s pretty clear. It’s telling you that the type of
ageEntryisWhereSelectEnumerableIterator2[System.Collections.Generic.KeyValuePair2[System.String,System.String],System.String]and that it can’t convert it. This is your major clue thatageEntryisn’t representing a number or something that can be converted to a number like you think it should be.Rather, it represents a query that filters and projects a certain sequence (in your case,
args). Basically,ageEntryknows how to filter through a sequence ofKeyValuePair<string, string>and project tostring. This is why you have to useEnumerable.Single. You’re saying “give me the one result from the query that results from doing all the filtering and projecting that you know how to do (by the way, throw an exception if there isn’t a single result).”