Bill
Bill

Reputation: 1417

How is a variable in a lambda expression given its value

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);

Upvotes: 4

Views: 226

Answers (3)

Ssithra
Ssithra

Reputation: 710

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++;
    }
}

Upvotes: 1

Roger Lipscombe
Roger Lipscombe

Reputation: 91845

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

Upvotes: 2

Mormegil
Mormegil

Reputation: 8071

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.

Upvotes: 4

Related Questions