Writing a remove name loop for a list

algorithm, c#, list

Solution

For a concise approach, use RemoveAll.

list.RemoveAll(person => person.FirstName == "David")

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.

class NameComparer : IComparer<Name>
{
    public int Compare(Name x, Name y) { 
        return x.First.CompareTo(y.First); 
    }
}
...
...
var comparer = new NameComparer();
var david = new Name { First = "David" };
int guess = list.BinarySearch(david, comparer);
int start, end;
start = list.FindLastIndex(guess, person => person.First != "David") + 1;
if (start > 0 && list[start].First == "David") {
    end = list.FindIndex(guess, person => person.First != "David");
    list.RemoveRange(start, end - start);
}

Problem

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!

Original source