Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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(3);
lst.Add(5);
lst.Add(-3);
lst.Add(4);
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,
So I want 5 and 6 from given list
like image 542
Kiran Joshi Avatar asked Sep 28 '18 12:09

Kiran Joshi


4 Answers

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.

like image 112
Tim Schmelter Avatar answered Sep 23 '22 03:09

Tim Schmelter


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);
}    
like image 45
juharr Avatar answered Sep 22 '22 03:09

juharr


One liner here:

var result = list.Reverse().TakeWhile(x=> x > 0).Reverse().ToList();
like image 39
eocron Avatar answered Sep 22 '22 03:09

eocron


Using Linq:

int result = (lst as IEnumerable<int>).Reverse().TakeWhile(x => x >= 0).Last();

It can throw exception if there is only one negative value at the end of list. However I don't know what data can be inside your list, so I cannot give you a perfect solution.

like image 20
apocalypse Avatar answered Sep 24 '22 03:09

apocalypse