gpt4 book ai didi

c# - lambda 参数如何映射到 TakeWhile 中?

转载 作者:太空狗 更新时间:2023-10-29 19:55:49 25 4
gpt4 key购买 nike

我正在使用 101 LINQ Samples in the MSDN page 学习 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);
}

此函数的目的是“使用 TakeWhile 返回从数组开头开始的元素,直到命中小于其在数组中的位置的数字。”

nindex 究竟是如何知道要采用哪个参数的? (即 n 如何知道它需要 5, 4, 1, 3, 9, 8, 6, 7, 2, 0index 知道它会递增 0, 1, 2, 3...) 吗?

最佳答案

因为重载是这样定义的。来自 MSDN

public static IEnumerable<TSource> TakeWhile<TSource>(
this IEnumerable<TSource> source,
Func<TSource, int, bool> predicate
)

predicate参数描述如下:

A function to test each source element for a condition; the second parameter of the function represents the index of the source element.

TSource 参数是项目,int 是索引。 bool 是返回值。

当您编写 (n, index) => ... 时,n 采用第一个参数 (TSource) 和 index 取第二个 (int)。

关于c# - lambda 参数如何映射到 TakeWhile 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com