gpt4 book ai didi

c# - 需要有关 Enumerable.Aggregate 函数的更多详细信息

转载 作者:太空狗 更新时间:2023-10-29 22:55:23 30 4
gpt4 key购买 nike

你能帮我理解吗,

       words.Aggregate((workingSentence, next) => + next + " " + workingSentence);   

从下面的代码片段?如果有人向我解释如何在 C# 1.1 中实现这一点,那就太好了。

(来自 MS 的片段)-

        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

最佳答案

您的示例的 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;

workingSentence 变量是一个累加器,它通过对现有累加器值和序列的当前元素应用一个函数,在循环的每次迭代中更新;这是由您的示例中的 lambda 执行的,在我的示例中由 foreach 循环的主体执行。

关于c# - 需要有关 Enumerable.Aggregate 函数的更多详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4184682/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com