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

前端 未结 4 1006
孤城傲影
孤城傲影 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:55

    FirstOrDefault() will turn the IEnumerable<int> into an int.

    Actually it takes the first occurance in the outputresult of your linq-query.

    0 讨论(0)
  • 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<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);
    }
    
    0 讨论(0)
  • 2021-01-19 01:58

    Well, that query might return more than one value, so you need to either use the .Single(), .First() or .FirstOrDefault() extension methods.

    Note, that Single() will only work if there is exactly one element in the list, First() will only work if there is at least one element in the list. FirstOrDefault() reverts to the default value (0) if there is no element in the list.

    Depending on what exactly you need you will have to choose :)

    0 讨论(0)
  • 2021-01-19 02:19

    What you want is this:

    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();             
            }
    

    The from clause produces a IEnumerable collection. You can convert this to an array with the .ToArray() extension

    0 讨论(0)
提交回复
热议问题