需要更多关于Enumerable.Aggregate函数的细节 [英] Need more details on Enumerable.Aggregate function

查看:161
本文介绍了需要更多关于Enumerable.Aggregate函数的细节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以帮我了解,

  words.Aggregate((workingSentence,旁边)=>接下来+ + + workingSentence); 



从下面的代码片段?这将是巨大的,如果有人能解释我才达到这在C#1.1。



(摘录自的 MS ) -

 串句=快速的棕色狐狸跳过懒狗 
//分割字符串为单个单词。
的String []字= sentence.Split('');
//前面加上每个单词的
//新句子扭转词序的开始。
串反转= words.Aggregate((workingSentence,旁边)=>
下一++ workingSentence);
Console.WriteLine(反向);
//此代码产生以下输出:
//
//狗懒过狐狸跳快速褐色的


解决方案

你的例子的总结部分翻译的东西大致是这样的:

 字符串workingSentence = NULL; 
布尔firstElement = TRUE;
的foreach(字符串中字旁)
{
如果(firstElement)
{
workingSentence =下一个;
firstElement = FALSE;
}
,否则
{
workingSentence =下一个++ workingSentence;
}
}
串反转= workingSentence;



workingSentence 变量是一个的累加器的是在通过施加功能到现有的累加器值和该序列的当前元素的循环的每次迭代更新;这是由你的榜样拉姆达并通过我的例子的foreach 循环体执行。


Can you help me to understand,

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

from below code snippet? and it would be great if someone explain me to achive this in C# 1.1.

(Snippet From 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

解决方案

The Aggregate part of your example translates to something roughly like this:

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 variable is an accumulator that is updated on each iteration of the loop by applying a function to the existing accumulator value and the current element of the sequence; this is performed by the lambda in your example and by the body of the foreach loop in my example.

这篇关于需要更多关于Enumerable.Aggregate函数的细节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆