bookmonkie
bookmonkie

Reputation: 449

Lambda expressions: index of an element in the array

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);

These are C# code taken from http://msdn.microsoft.com/en-us/library/bb397687.aspx

I understand the first two lambda expressions just fine by considering n as an element of the array "numbers".

However the third lambda expression is really confusing with "index". Is (n,index) one of the lambda parameters well established for arrays? Is this a convention?

Upvotes: 0

Views: 4292

Answers (1)

Lee Grissom
Lee Grissom

Reputation: 9953

When TakeWhile iterates over the collection:

n is the value of the element
index is the index of the element

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
// As TakeWhile iterates over the array: 
//   "n" is the value of the element
//   "index" is the index of the element
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
foreach(var n in firstSmallNumbers)
    Console.WriteLine(n);

Output:

5
4

Run this at: https://dotnetfiddle.net/4NXRkg

Upvotes: 1

Related Questions