Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - Get the Index of the Last Non-Zero Number of Array

Tags:

arrays

c#

.net

linq

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;

like image 829
BSalita Avatar asked Dec 27 '12 03:12

BSalita


2 Answers

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 ?

like image 165
Ani Avatar answered Sep 29 '22 08:09

Ani


List<T> has an extension method for this called FindLastIndex

var index = new int[] { 0, 2, 1}.ToList().FindLastIndex(x => x > 0);
like image 24
Khan Avatar answered Sep 29 '22 06:09

Khan