Remove an item from a List

2011-03-08


In some cases, if you want to remove an item from a List in C#, you can not use foreach and remove the item, because if you remove one item, the original list has changed, the foreach loop can not work correctly.

Remove an item from a List in C#?

Here We collected some nice code blocks to remove an item from a list:

1:

for (int idx = list.Count – 1; idx >= 0; idx–)
{
if (some conditions)

 list.RemoveAt(idx);
}

2: To remove selected item in multiselect list box:

for (int i=lbx_ProdMaster.Items.Count ; i>0 ; i–)
{
if(lbx_ProdMaster.Items[i-1].Selected == true)
{
lbx_ProdMaster.Items.RemoveAt(i-1);
}
}

3: (delete all)

While (list it not empty)
{
Delete First item
}

4:

playerShots.RemoveAll(delegate(Shot s)
{
return s.Location.Y < 0;
});

5: remove all:

List<T>.RemoveAll(Predicate<T> match) 

from MSDN

6:

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;
int itemCount = listItems.Count;

for (int k=0; k<itemCount; k++)
{
    SPListItem item = listItems[k];

    if (TextBox2.Text==item["Employee"].ToString())
    {
        listItems.Delete(k);
    }
}

7: Use the class System.Collections.IEnumerator

IEnumerator iterator = list.GetEnumerator();
do
{
//In here you could some kind of check
//For which items you want to remove list.Remove(iterator.Current);
} while (iterator.MoveNext());

8:

list.Where().ToList().Foreach(item => list.Remove(item));

9:

//removes all even numbers from list:
NumberList.RemoveAll(delegate(int x) { return x%2 == 0; });