0
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?

3
  • index meens index of element in array and this expression returns all the elements in the numbers array until a number is encountered whose value is less than its position.OK ? Commented Jul 24, 2014 at 19:21
  • It's just part of the delegate that TakeWhile() accepts. You can read about it here: msdn.microsoft.com/en-us/library/vstudio/…. Check out the predicate parameter. Commented Jul 24, 2014 at 19:23
  • What did you find when you looked at the documentation of that particular method, and what aspect of that did you find confusing? Commented Jul 24, 2014 at 19:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.