c# - 多参数linq表达式如何初始化它们的参数?

标签 c# linq lambda

在此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/

相关文章:

pandas - 我想在列上使用 lambda 将 DataFrame 拆分为 2 个 df

c# - 使用 using 范围时,是否必须调用 Close 方法?

c# - LINQ 时间戳 - 自动更新时间戳列?

c# - 生成 n 元笛卡尔积示例

c# - 从两个数据表中选择 Linq to SQL 中的不同和日期差异

c# - 检查是否是 bool 值?在动态 Lambda 中为真

lambda 表达式中的 C# 未检查关键字

c# - 访问在 HttpActionContext 中作为 POST 发送的查询字符串变量

c# - 如何让 OpenApi Generator 正确转换 Dictionary<int, string>?

c# - 如何轻松判断 Ninject 是否可以解析类