Question

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);
Was it helpful?

Solution

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.

OTHER TIPS

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

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++;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top