Does Foreach not go through all subjects?

I have this code:

       foreach (var item in ListView1.Items)
            {
                ListView1.Items.Remove(item);
                ListView21.Items.Add(item);
            }

does the cycle stop at half the elements?

Any idea?

EDIT

Well, maybe this is my mistake, I need to clarify that this is an UltraListView control from Infrajistics, where I cannot add an item to another list unless I delete it or hide it from the original list.

But thanks, most of the comments regarding do not change the list in the loop were correct, so this code works:

           foreach (var item in listView1.Items)
            {
                var i = item.Clone(true);
                listView2.Items.Add(i);
            }
            listView1.Items.Clear();

Thank,

+3
source share
8 answers

You cannot modify an iterated collection, it must die with an exception (or in undefined mode). Try making a copy of the array:

   foreach (var item in ListView1.Items.ToArray())
   {
       ListView1.Items.Remove(item);
       ListView21.Items.Add(item);
   }

EDIT:

in fact, your sample code can be obtained by writing:

ListView21.Items.AddRange(ListView1.Items);
ListView1.Items.Clear();

( , , , , ). .NET2.0, linq , ,.NET3.5.

+15

, . for ( 0).

for (int i = ListView1.Items.Count - 1; i >= 0; i--)
{
    var item = ListView1.Items[i];
    ListView1.Items.Remove(item);
    ListView21.Items.Insert(0, item);
}
+9

, , . for.

for(int index = Items.Count; index > 0; index--)
{
    .......
    // use Add and RemoveAt
}

EDIT: . . AddRange Clear .

+2

- ? .

0

WinForms, :

ListViewItem[] items = ListView1.Items.ToArray();
ListView1.Items.Clear();
ListView21.Items.AddRange(items);
0
0

, , . , . , , ?

foreach (var item in ListView1.Items)
{
    ListView21.Items.Add(item);
}
ListView1.Items.Clear();   // remove all

PS: ASP.NET WinForms?

0

, . :

for(int i=0; i < ListView1.Items.Count-1; i++)
{
       ListView21.Items.Add(ListView1.Items[i]);
       ListView1.Items.RemoveAt(i);
}
-1

Source: https://habr.com/ru/post/1754562/


All Articles