C# lambda 幕后

标签 c# lambda

对于没有使用 Lambda Expresstions 经验的人,下面的代码让它看起来很神奇:

int totalScore = File.ReadLines(@"c:/names.txt")
            .OrderBy(name => name)
            .Select((name, index) => {
                int score = name.AsEnumerable().Select(character => character - 96).Sum();
                score *= index + 1;
                return score;
            })
            .Sum();

是什么让 name 引用集合中的元素,更有趣的是,是什么让 index 引用元素的索引?

显然这不是魔法,除了理解Delegates (也许还有别的东西?),Lambda 表达式是如何工作的?

最佳答案

没有魔法,全部Select正在做正在执行

    public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector) {
        if (source == null) throw Error.ArgumentNull("source");
        if (selector == null) throw Error.ArgumentNull("selector");
        return SelectIterator<TSource, TResult>(source, selector);
    }

    static IEnumerable<TResult> SelectIterator<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, int, TResult> selector) {
        int index = -1;
        foreach (TSource element in source) {
            checked { index++; }
            yield return selector(element, index);
        }
    }

selector是你传入的函数,是一个Func<TSource, int, TResult>这意味着它有两个参数,第一个参数可以是任何类型,第二个参数是 int并且返回类型可以是任何类型。

您使用的函数是匿名函数

(name, index) => {
            int score = name.AsEnumerable().Select(character => character - 96).Sum();
            score *= index + 1;
            return score;
        }

这和

是一样的
private int SomeFunction(string name, int index)
{
    int score = name.AsEnumerable().Select(character => character - 96).Sum();
    score *= index + 1;
    return score;
}

所以 Select通过 nameindex值并调用您的函数。

关于C# lambda 幕后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955816/

相关文章:

c# - UWP 应用程序 : Could not load file or assembly 'System. Runtime.WindowsRuntime,版本 = 4.0.14.0

c# - 如何在 C# 中锁定/解锁 Windows 应用程序窗体

c# - 如何查看 lambda 表达式的 SQL 查询

excel - 函数的条件分支会引发错误的圆引用错误

c# - 用于选择索引 > x 的所有项目的 Lambda 表达式

C# 多行 lambda 表达式

c# - 在 Try/Catch 中处理 Application.ThreadException 和包装 Application.Run 之间的区别

c# - mscorlib.dll 中发生“System.Net.Http.HttpRequestException”,但未在用户代码中处理

C# IBM MQ 客户端发送我自己的 messageId

c++ - 使用 C++ Lambda 函数作为 Qt 中的槽是否有助于保持库的二进制兼容性?