How a variable in a lambda expression gives its value

How does index in the example below get its value? I understand that n is automatically obtained from the numbers source, but although the meaning is clear, I don’t see how the index is assigned its value:

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

Signature TakeWhile :

 public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate); 
+4
source share
3 answers

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

There is also a β€œsimpler” version of the function that provides only values ​​in a sequence; see MSDN .

+4
source

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

+2
source

Everything becomes clear while 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++; } } 
+1
source

Source: https://habr.com/ru/post/1337604/


All Articles