lambda参数如何在TakeWhile中映射?

C.J*_*.J. 7 c# linq lambda

我正在使用MSDN页面中101 LINQ Samples学习LINQ ,我遇到了这段代码:

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);

foreach (var n in firstSmallNumbers)
{
    Console.WriteLine(n);
}
Run Code Online (Sandbox Code Playgroud)

这个函数的目的是"使用TakeWhile返回从数组开头开始的元素,直到命中的数字小于它在数组中的位置."

究竟是怎么nindex知道哪些参数取?(即n知道它将如何知道5, 4, 1, 3, 9, 8, 6, 7, 2, 0以及如何index知道它会增加0,1,2,3 ......)?

Bra*_*NET 9

因为过载是这样定义的.来自MSDN

public static IEnumerable<TSource> TakeWhile<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, int, bool> predicate
)
Run Code Online (Sandbox Code Playgroud)

predicate论点描述如下:

用于测试条件的每个源元素的函数; 函数的第二个参数表示源元素的索引.

TSource参数是项目,并且int是该指数.这bool是返回值.

当你写(n, index) => ...n取第一个参数(TSource),并index采取第二(int).

  • @CJ就是这样.您正在定义一个匿名方法,参数名称由您决定. (3认同)
  • @CJ尝试并找出答案.你已经有了代码来完成它. (3认同)