在此post中,该问题的解决方案是:list.Where((item, index) => index < list.Count - 1 && list[index + 1] == item)
多参数的概念(即(item, index)
)让我有些困惑,我不知道正确的词来缩小我的Google搜索结果范围。所以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/