在此post问题的解决方案是:
list.Where((item, index) => index < list.Count - 1 && list[index + 1] == item)
多参数的概念(即 (item, index)
)让我有点困惑,我不知道正确的词来缩小我的谷歌搜索结果。所以 1) 那叫什么?更重要的是,2) 不可枚举变量是如何初始化的?在这种情况下,index
是怎样的?编译为 int 并初始化为 0?
谢谢。
最佳答案
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
这里的微妙之处在于 Where
有一个接受 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;
}
}
}
关于c# - 多参数linq表达式如何初始化它们的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4216031/