Updated answer:
If we are not allowed to use the RemoveAll or LINQ functions that do all the work for us, this is the way to do it more "manually":
List<Person> newPersons = new List<Person>(); foreach (Person person in persons) { if (person.FirstName != "David") newPersons.Add(person); } persons = newPersons();
Building a new list is very fast in .NET. Deleting items one by one is slow, because each item to be deleted must first be found in the list, and then when it is deleted, the rest of the list must be moved up to fill the gap. This is much slower than the method described above.
To make the delete operation even faster, the list can be saved in sorted order or grouped by name. But then the initial creation of the list will be slower.
Old answer:
It seems you are interested in a concise solution, not optimal performance. If you are using .NET 3.5, you can use this:
persons = persons.Where(person => person.FirstName != "David").ToList();
Oh, and List has a RemoveAll method:
names.RemoveAll(person => person.FirstName == "David");
(Note Jimmy posted the RemoveAll idea before I did it.)
source share