Easy Way to Remove an Item from a List in C#

To remove an item from a list in C#, I often found myself going the old-school route and iterating through the list backwards with a for loop, like this:

for (int i = myList.Count - 1; i >= 0; i--)
{
    if (myList[i].Id == idToDelete)
    {
        myList.RemoveAt(i);
        break;
    }
}

I’ll let this pass in JavaScript, but surely C#  must have an easier way. The obvious candidate is the List(T).Remove method. However, it is also kind of cumbersome. For example, to remove an item based on my Id property, you have to implement the IEquatable interface (as well as override the Equals method, to be safe).

The simplest approach is to use the List(T).RemoveAll method. It takes a delegate as an argument, so you can easily pass in a lambda, like this:

myList.RemoveAll(j => j.Id == idToDelete);

Obviously only use this method if you want to remove all items that match your criteria from the list. Also, both Remove and RemoveAll are O(n) operations, so if you need to scale well, probably best to use a HashSet.

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: