对于没有使用 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
通过 name
和 index
值并调用您的函数。
关于C# lambda 幕后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31955816/