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

Since it's a list you can use FindLastIndex

int index = lst.FindLastIndex(i => i < 0); // it's value is lst[index]
IEnumerable<int> allPositiveAfterLastNegative = lst.Skip(index + 1);

This handles also the cases that there is no negative value or it is at the beginning or end.


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);
}    

One liner here:

var result = list.Reverse().TakeWhile(x=> x > 0).Reverse().ToList();

Tags:

C#