How to remove negative values ​​from the <int> list?

I end up with a bunch of ints in my list (named "listInts").

This should not surprise anyone.

My problem is that I do not want any negative numbers there, but it is possible to have three, especially -1, -2 and -3.

I can clumsily delete them through:

if (listInts.Contains(-1) {
    int i = listInts.IndexOf(-1);
    listInts.Remove(i);
    // etc.
}

... but I know that it exhorts the smell of code, more frightening than a whole ferret wand.

What's better?

+5
source share
2 answers

I would use LINQ:

listInts = listInts.Where(i => i >= 0).ToList();

Depending on how this will be used, you can also avoid the call ToList()and not save the values:

var positiveInts = listInts.Where(i => i >= 0);

This will still allow you to list as needed.

, List<T>.RemoveAll :

listInts.RemoveAll(i => i < 0);

, , , , , , ( ), LINQ.

+8
listInts.RemoveAll(t => t < 0)
+9

All Articles