4

How does index in the below example obtain its value? I understand that n is automatically obtained from the source numbers, but, while the meaning is clear, I do not see how index is given its value:

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

The signature of TakeWhile is:

public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
Bill
  • 1,407
  • 1
  • 15
  • 22
  • Are you asking how it works out being well-typed, or what's the meaning of index/how `TakeWhile` is defined? –  Jan 29 '11 at 17:53
  • @delnan: I thought I was asking a general question about lambdas, but based on the responses, I was really asking a question about how TakeWhile is using the lambda. I understand that the type of n can be inferred from the type of the members of numbers, and the type of index is defined by Func. – Bill Jan 29 '11 at 18:18

3 Answers3

4

This version of TakeWhile supplies the index of the source element in the sequence as the second parameter to the predicate. I.e. the predicate is called as predicate(5, 0), then predicate(4, 1), predicate(1, 2), predicate(3, 3) etc. See the MSDN documentation.

There is also a “simpler” version of the function, supplying only the values in the sequence, see MSDN.

Mormegil
  • 7,955
  • 4
  • 42
  • 77
  • Thanks .. it occurred to me after posting my question that TakeWhile must provide the value to index .. I am just getting used to parsing out inferred values from supplied values, and lambda usage in general. – Bill Jan 29 '11 at 18:25
2

The index is generated by the implementation of TakeWhile, which might look a bit like this.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
1

Things become clear as long as you figure out how TakeWhile can be implemented :

public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
{
    int index = 0;
    foreach (TSource item in source)
    {
        if (predicate(item, index))
        {
            yield return item;
        }
        else
        {
            yield break;
        }
        index++;
    }
}
Ssithra
  • 710
  • 3
  • 8