LINQ:无法将类型'System.Collections.Generic.IEnumerable <int>'隐式转换为'int'

Dar*_*age 5 c# linq

我从以下代码中收到错误:

int dreamX[];

private void Form1_Load(object sender, EventArgs e)
{ 
    sumX();
}

private void sumX()
{
    for (var i = 0; i < 8; i++)
    {
        dreamX[i] =
            from Control control in Controls
            where
                control.GetType() == typeof(TextBox)
                && control.Name.StartsWith("box")
            select Convert.ToInt32(((TextBox)control).Text);
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误,如何显式转换此错误.

"无法将类型'System.Collections.Generic.IEnumerable -int-'隐式转换为'int'"

Joe*_*oey 13

那么,该查询可能返回多个值,所以你需要或者使用.Single(),.First().FirstOrDefault()扩展方法.

请注意,Single()只有在列表中只有一个元素First()时才会起作用,只有在列表中至少有一个元素时才有效.FirstOrDefault()如果列表中没有元素,则恢复为默认值(0).

根据您的确切需要,您必须选择:)


Joe*_*orn 11

这么多错了.

首先,您尝试将可能很多转换的整数分配给数组中的单个整数.这就是错误消息告诉你的内容.

此外,您展示的代码中没有任何地方是该数组已初始化.因此,即使你打电话给.FirstOrDefault()你,你最终会得到一个NullReferenceException.如果你能提供帮助,最好不要使用arrarys.坚持使用IEnumerable.

另外,你是linq查询有一个额外的步骤; 而不是检查Controls集合中每个控件的类型,您应该调用它的.OfType()方法.

最后,linq的美妙之处在于你甚至不必编写for循环.您只需编写一个语句来评估所有文本框.

IEnumerable<int> dreamX;

private void Form1_Load(object sender, EventArgs e)
{ 
    sumX();
    int totalX = dreamX.Sum();
}

private void sumX()
{
    dreamX = from control in Controls.OfType<TextBox>()
             where control.Name.StartsWith("box")
             select Convert.ToInt32(control.Text);
}
Run Code Online (Sandbox Code Playgroud)


Dab*_*rnl 8

你想要的是这个:

int[] dreamX;
private void Form1_Load(object sender, EventArgs e)
        { 
         sumX();
        }
 private void sumX()
        {
                dreamX =( from Control control in Controls                  
                         where control.GetType() == typeof(TextBox) &&
                               control.Name.StartsWith("box")
                         select Convert.ToInt32(((TextBox)control).Text))
                                       .ToArray();             
        }
Run Code Online (Sandbox Code Playgroud)

from子句生成IEnumerable 集合.您可以将其转换为具有.ToArray()扩展名的数组