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?
We use the removeIf method to delete all negative values. values. removeIf(val -> val < 0); All negative numbers are removed from the array list.
In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive.
An int is signed by default, meaning it can represent both positive and negative values.
listInts.RemoveAll(t => t < 0)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With