多参数linq表达式如何初始化其参数?

E.B*_*ach 11 c# linq lambda

在这篇文章中,问题的解决方案是:

list.Where((item, index) => index < list.Count - 1 && list[index + 1] == item)

多参数(即(item, index))的概念对我来说有点令人费解,我不知道缩小谷歌搜索结果的正确用语.所以1)那叫什么?更重要的是,2)非可枚举变量如何初始化?在这种情况下如何index编译为int并初始化为0?

谢谢.

Mar*_*ell 13

Lambda表达式有各种语法选项:

() => ... // no parameters
x => ... // single parameter named x, compiler infers type
(x) => ... // single parameter named x, compiler infers type
(int x) => ... // single parameter named x, explicit type
(x, y) => ... // two parameters, x and y; compiler infers types
(int x, string y) => ... // two parameters, x and y; explicit types
Run Code Online (Sandbox Code Playgroud)

这里的细微之处在于它Where有一个重载接受a Func<T, int, bool>,分别代表索引(并返回bool匹配).所以它是Where提供索引的实现 - 类似于:

static class Example
{
    public static IEnumerable<T> Where<T>(this IEnumerable<T> source,
        Func<T, int, bool> predicate)
    {
        int index = 0;
        foreach (var item in source)
        {
            if (predicate(item, index++)) yield return item;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)