How to get positive values after last negative value in a list?

  • A+

I want all the positive integer values after the last negative value.
Below is list of integer values:-

List<int> lst = new List<int>(); lst.Add(1); lst.Add(5); lst.Add(-3); lst.Add(-4); lst.Add(5); lst.Add(6); 

I tryed

lst.Skip(lst.Max(0, lst.Count - 1)).ToList(); 

Expected Output

Last positive values after last negative value:   in example list last negative value is -4 and last positive values are 5, 6  


To get all the values after the last negative you can do

var positivesAfterLastNegative = lst.Reverse().TakeWhile(x => x >= 0).Reverse().ToList() 

Basically that starts at the end goes until it finds a negative then reverses the results so they're back in the correct order.

Note: I would only suggest doing this with a list or array. It's going to have bad performance for something that requires iterating to get to the end. In that case you could do the following instead.

List<int> results = new List<int>(); foreach(var item in lst) {     if(item < 0)     {         results.Clear();     }     else     {         results.Add(item);     } } 

That will add non-negative values to the list until it hits a negative value and then it will clear the list, resulting in only the values after the last negative value.

And if you prefer a non Linq solution for something that's indexed you can do this

List<int> results = new List<int>(); for(int i = lst.Count - 1; i >= 0; i--) {     if(lst[i] < 0)     {         break;     }      results.Insert(0,item); }     


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: