Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query throws an InvalidCastException?

Tags:

c#

casting

linq

I was roaming around in different sites for casting techniques and I constructed the following code to cast to from float to int as shown below

var floatList = new float[] { 2.7f, 3.1f, 4.5f };
var intList = from int test1 in floatList 
              select test1;

foreach (var v in intList) 
    Console.Write("{0} ", v.ToString());

But above code throws an InvalidCastException. Why is this? I thought it is supposed to print 3,3 and 4.

like image 756
Neel Avatar asked May 07 '14 09:05

Neel


Video Answer


2 Answers

A LINQ clause of the form:

from X x in y

is equivalent to

y.Cast<X>()

and then using x as the range variable later. The rest of your query is degenerate, so your code is equivalent to:

var intList = floatList.Cast<int>();

Now Enumerable.Cast() does not do conversions like this - it just does reference conversions and boxing/unboxing conversions. For any other conversions, you need Select:

var intList = floatList.Select(x => (int) x);

Or if you really to use a query expression:

var intList = from x in floatList select (int) x;

... but personally for simple queries like this, I wouldn't use a query expression - I'd just use the method call as shown above.

like image 67
Jon Skeet Avatar answered Nov 15 '22 09:11

Jon Skeet


This is because there are not ints in floats and by int i you're specifying to look for ints, causing an internal cast that doesn't work (like int i = 2.7f;).

I think this would be the way it works:

var ints = from f in floats 
           select (int)f;
like image 40
Thorsten Dittmar Avatar answered Nov 15 '22 07:11

Thorsten Dittmar