I get an error from the following code:
int dreamX[];
private void Form1_Load(object sender, EventArgs e)
{
sumX();
}
private void sumX()
{
for (v
FirstOrDefault()
will turn the IEnumerable<int>
into an int
.
Actually it takes the first occurance in the outputresult of your linq-query.
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);
}
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 :)
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