Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top