Is there a Linq expression that returns the index of the last non-zero value in an array? I'm not interested in an extension, only a simple linq expression.
I'm imagining something like this pseudo code:
int index = {0, 2, 1}.LastOrDefaultAt(i => i > 0);
The returned value should be 2;
You can use the Array.FindLastIndex<T>
method for this:
int index = Array.FindLastIndex(myIntArray, item => item > 0);
I notice that you mention "non-zero" rather than "greater than zero" in your question text. Should your predicate be: item => item != 0
?
List<T>
has an extension method for this called FindLastIndex
var index = new int[] { 0, 2, 1}.ToList().FindLastIndex(x => x > 0);
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