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
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With