Pages

Saturday, July 17, 2010

removing many items from list

Let's take a look a screenshoot first :

Lets suppose you have a list, and you want to delete selected list.
For the first time, I am using foreach, but it throws an exception. Yes of course, item count will change after removing. So the foreach constraint will changed while looping. So it can't use foreach. It must use loop.
for(int i = 0; i<mList.Count; i++)
  It's wrong because m.List.Count will change after deletion. You must create buffer to accomodate this.
int mCount = mList.Count;
for(int i = 0; i < mCount; i++)
mList.RemoveAt(table.Rows[i].index);

It's also remove unwanted items. Its because after deletion, index also change. For example, when you remove index 1 and then index 3, what actually happens is you delete index 1, and then index 2 become index 1, and soon. When you remove index 3, actually you remove the item who has index of 4 before deletion loop. Its now become index 3 and this who will be deleted. Because the index before deleted items never change, you can reverse the loop:
 int mCount = mList.Count - 1;
for(int i = mCount; i >=0; i--)
{
mList.RemoveAt( table.Rows[i].index);
}

No comments: