4

在下面的例子中如何index获得它的价值?我知道 n 是从 source 自动获得的numbers,但是,虽然含义很清楚,但我看不到 index 是如何赋予其值的:

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

的签名TakeWhile是:

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

3 回答 3

4

这个版本的 TakeWhile 提供序列中源元素的索引作为谓词的第二个参数。即谓词称为谓词(5, 0),然后称为谓词(4, 1),谓词(1, 2),谓词(3, 3)等。请参阅MSDN文档

该函数还有一个“更简单”的版本,仅提供序列中的值,请参阅MSDN

于 2011-01-29T17:56:16.947 回答
2

索引是由 的实现生成的TakeWhile,它可能看起来有点像这样

于 2011-01-29T17:57:08.570 回答
1

只要您弄清楚如何实现 TakeWhile,事情就会变得清晰:

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++;
    }
}
于 2011-05-26T20:56:55.587 回答