0

Here is my code:

 int k = panel.Controls.OfType<DataGridView>().Count<DataGridView>();
            foreach (Control control in panel.Controls.OfType<DataGridView>())
            {
                panel.Controls.Remove(control);
            }

I have 4 DataGridView objects on panel that are created at runtime with the names 0, 1, 2, and 3, and "k" its shown correct value(4). But my foreach loop's first step is "0", second is "2", and then the loop ends. It skips two object and I don't know why.

If I put a second and third foreach statement, the result is correct. Why is that so?

1
  • add materialization - .ToArray() - foreach (Control control in panel.Controls.OfType<DataGridView>().ToArray()) {panel.Controls.Remove(control);} Commented Oct 14, 2018 at 20:22

2 Answers 2

2

In the first loop your Control is Zero. You remove the control. Your next loop gets the next Control. Since its already returned the first control, it now returns the second Control, but since you've removed the Zero control the second Control is now 2.

The key to understanding this behaviour is that the OfType() returns an iterator, not a list. If you returned OfType().ToList() you would get a concrete list that would not be changed when you alter the list you derived it from.

So;

IList<object> x = underlyingList.OfType<object>() returns an iterator.
List<object> y = underlyingList.OfType<object>().ToList() returns a concrete list.
Sign up to request clarification or add additional context in comments.

Comments

0

When you delete objects in the list you're iterating over you also alter its length.

  1. First iteration you're at index 0 and length 4.
  2. Second iteration is at index 1 (originally this item was index 2) and length 3.
  3. Then your loop will terminate because you're at index 2 but there's no element at that index anymore because the ones who were there are now at index 0 and 1.

If you want to remove all elements this way you can iterate over the list backwards instead, this way you won't offset the list and making you miss the elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.