I’m looking to try to make an efficient delete method to work on a list. This situation is as follows:
Say for e.g. I have a (potentially) massive list of names:
Alex Smith
Anna Hobb
Bertie Blackman
Bill Clinton
David Smith
David Warner
George Jung
George Washington
William Wobbits
Lets say that this is a List<Person> with Person having properties FirstName and LastName. As in the example, there is the possibility for two people sharing same FirstName. What I need to do is go through the list and delete all Davids, for example.
I was looping through finding all davids, adding to a list DeletePerson, then looping through again for each DeletePerson and removing. I’m sure there would be a more efficient method? Efficiency isn’t critical in this app but it just seems a long winded way to do it, also I guess as after the letter D in the first name we know we won’t be adding any more to the DeletePerson list (assuming the list is sorted alphabetically)
Thanks!
For a concise approach, use RemoveAll.
for an (possibly? I haven’t run any benchmarks) efficient approach based on the order in a list, use List.RemoveRange — but you’ll have to find the indexes.