LINQ查询抛出InvalidCastException?

Nee*_*eel 6 c# linq casting

我在不同的网站中漫游以进行投射技术,我构建了以下代码以从中float转换int为如下所示

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());
Run Code Online (Sandbox Code Playgroud)

但是上面的代码抛出了一个InvalidCastException.为什么是这样?我以为它应该打印3,34.

Jon*_*eet 15

形式的LINQ子句:

from X x in y
Run Code Online (Sandbox Code Playgroud)

相当于

y.Cast<X>()
Run Code Online (Sandbox Code Playgroud)

然后再x用作范围变量.您的查询的其余部分是简并的,因此您的代码等效于:

var intList = floatList.Cast<int>();
Run Code Online (Sandbox Code Playgroud)

现在Enumerable.Cast()不会做这样的转换-它只是不引用转换和装箱/拆箱转换.对于任何其他转换,您需要Select:

var intList = floatList.Select(x => (int) x);
Run Code Online (Sandbox Code Playgroud)

或者,如果您真的要使用查询表达式:

var intList = from x in floatList select (int) x;
Run Code Online (Sandbox Code Playgroud)

...但是对于像这样的简单查询,我不会使用查询表达式 - 我只是使用上面显示的方法调用.


Tho*_*mar 5

这是因为没有intS IN floatsint i你指定找intS,造成内部投不工作(像int i = 2.7f;).

我认为这将是它的工作方式:

var ints = from f in floats 
           select (int)f;
Run Code Online (Sandbox Code Playgroud)