LINQ: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'

前端 未结 4 1160
孤城傲影
孤城傲影 2021-01-19 01:19

I get an error from the following code:

int dreamX[];

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

private void sumX()
{
    for (v         


        
4条回答
  •  半阙折子戏
    2021-01-19 01:56

    So many things wrong with that.

    First of all, you're trying to assign what is potentially many converted integers to a single integer within an array. That's what the error message is telling you.

    Additionally, nowhere in the code you showed is that array ever initialized. So even if you call something like .FirstOrDefault() you'll end up with a NullReferenceException. Best not to use arrarys at all if you can help it. Just stick with IEnumerable.

    Also, you're linq query has an extra step; rather than checking the type of each control in the Controls collection you should call its .OfType() method.

    Finally, the beauty of linq is that you don't even have to write the for loop. You can just write one statement that evaluates all your textboxes.

    IEnumerable dreamX;
    
    private void Form1_Load(object sender, EventArgs e)
    { 
        sumX();
        int totalX = dreamX.Sum();
    }
    
    private void sumX()
    {
        dreamX = from control in Controls.OfType()
                 where control.Name.StartsWith("box")
                 select Convert.ToInt32(control.Text);
    }
    

提交回复
热议问题