LINQ: It is not possible to implicitly convert the type 'System.Collections.Generic.IEnumerable <int>' to 'int'

I get an error from the following code:

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

I get this error as an explicit conversion of this.

"It is not possible to implicitly convert the type 'System.Collections.Generic.IEnumerable -int-' to 'int'"

+4
source share
4 answers

What you want is:

 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 creates an IEnumerable collection . You can convert this to an array with the extension .ToArray ()

+7
source

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

Please note that Single() will only work if there is only one element in the list, First() will only work if there is at least one element in the list. FirstOrDefault() returns the default value (0) if there is no item in the list.

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

+13
source

So much is wrong.

First of all, you are trying to assign potentially many converted integers to a single integer inside an array. This error message informs you.

Also, nowhere in the code that you showed is this array ever initialized. Therefore, even if you call something like .FirstOrDefault() , you will get a NullReferenceException . Better not to use arrivals at all if you can help. Just stick with IEnumerable.

In addition, your linq query has an extra step; instead of 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 need to write a for loop. You can simply write one statement that evaluates all of your text fields.

 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); } 
+11
source

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

In fact, this takes the first appearance in your outputresult of your linq query.

+3
source

All Articles