Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove negative values from a List<int>?

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?

like image 471
B. Clay Shannon-B. Crow Raven Avatar asked Jun 02 '12 00:06

B. Clay Shannon-B. Crow Raven


People also ask

How do you remove negative numbers from a list in Java?

We use the removeIf method to delete all negative values. values. removeIf(val -> val < 0); All negative numbers are removed from the array list.

How do you get rid of a negative in Python?

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.

Can int take negative values?

An int is signed by default, meaning it can represent both positive and negative values.


2 Answers

listInts.RemoveAll(t => t < 0)
like image 172
Porco Avatar answered Oct 12 '22 23:10

Porco


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.

like image 32
Reed Copsey Avatar answered Oct 13 '22 00:10

Reed Copsey