How to remove negative values from a List<int>?
algorithm, arraylist, c#, generics
Solution
I would use LINQ:
listInts = listInts.Where(i => i >= 0).ToList();
Depending on how this is going to be used, you could also avoid the `ToList()` call and not resave the values:
var positiveInts = listInts.Where(i => i >= 0);
This will still let you enumerate as needed.
If you need to change the list in place, `List<T>.RemoveAll` is actually a more efficient method:
listInts.RemoveAll(i => i < 0);
However, I do not prefer this as it's a method that causes side effects, and tends to be confusing (hence hampering maintenance) if you're using other LINQ extension methods.
Problem
I'm ending up with a bunch of ints in my List (named "listInts"). That should not surprise anybody. My problem is I don't want any negative numbers in there, but there is the possibility of having three, specifically -1, -2, and -3. I can clumsily remove them via: ``` if (listInts.Contains(-1) { int i = listInts.IndexOf(-1); listInts.Remove(i); // etc. } ``` ...but I know this exhudes a code smell stenchier than a whole passle of polecats. What is a better way?