你能帮我理解吗
words.Aggregate((workingSentence, next) => + next + " " + workingSentence);
从下面的代码片段?如果有人解释我如何在 C# 1.1 中实现这一点,那就太好了。
(摘自MS http://msdn.microsoft.com/en-us/library/bb548651.aspx)-
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words.
string[] words = sentence.Split(' ');
// Prepend each word to the beginning of the
// new sentence to reverse the word order.
string reversed = words.Aggregate((workingSentence, next) =>
next + " " + workingSentence);
Console.WriteLine(reversed);
// This code produces the following output:
//
// dog lazy the over jumps fox brown quick the
The Aggregate
你的例子的一部分大致翻译成这样:
string workingSentence = null;
bool firstElement = true;
foreach (string next in words)
{
if (firstElement)
{
workingSentence = next;
firstElement = false;
}
else
{
workingSentence = next + " " + workingSentence;
}
}
string reversed = workingSentence;
The workingSentence
变量是一个累加器通过将函数应用于现有累加器值和序列的当前元素,在循环的每次迭代中更新;这是由示例中的 lambda 和 的主体执行的foreach
在我的例子中循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)