C# – Linq – Get the Index of the Last Non-Zero Number of Array

arraysclinqnet

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;

Best Answer

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 ?