I’ve already written about how to add or insert an item to a C# List, but what about if you want to remove an item from a C# List? In this post I’ll provide examples showing how to remove a string from a list, remove an integer from a list, and how to remove a custom object from a C# List.
If we start with a list of strings, in this case sports :
List<string> sports = new List<string> {"Tennis", "Baseball", "Swimming", "Skiing", "Running", "Karate"};
We want to remove Skiing from the list, and would do so by using the Remove method on the list, by providing the item as a property, in this case a string. If a match for the item is found, it will be removed:
sports.Remove("Skiing");
So if we were dealing with a list of integers :
List<int> tickets = new List<int> { 54, 12, 3, 41, 15, 16, 702, 89, 109 };
… we’d remove an item like this, again specifying the item that needs to be removed, in this case an integer:
tickets.Remove(12);
It’s more than likely that in a real application you’ll be dealing with a list of custom objects, so next I’ll explain how to remove custom objects from a list.
Remove a custom object from a C# List
I’ll start again with the list of drinks similar to my previous post, and will then remove an item using it’s known index (position) in the List, using RemoveAt:
List<Drink> drinks = new List<Drink> { new Drink{ Name = "Sambucca", Id=9 }, new Drink{ Name = "Prosecco", Id=192 }, new Drink{ Name = "Vodka and orange", Id=17 }, new Drink{ Name = "Martini", Id=43 }, new Drink{ Name = "Apple Juice", Id=149 }, new Drink{ Name = "Mojito", Id=44 }, new Drink{ Name = "Pale Ale", Id=18 } }; WriteList(drinks, "Drinks"); Console.WriteLine("Now remove the Apple Juice from the list of drinks using it's index:"); drinks.RemoveAt(4); WriteList(drinks, "Amended drinks list");
If you run this code, you’ll see something like this:
However, to remove an item from the List by it’s value, the object class, in this case Drink, needs a new method added, as follows:
//add to Drink class public bool Equals(Drink other) { return Name.Equals(other.Name); }
Let’s say we have added a drink to the list :
Drink coke = new Drink { Name = "Coke", Id = 55 }; drinks.Add(coke);
… and then to remove the drink from the list simply involves doing this:
drinks.Remove(coke);
Summary
I’ve explained how to remove a string from a list of strings, an integer from a list of integers, and how to remove a custom object from a list in C#.