简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM