3

我试图想出最好的表达方式来解决我的确切问题,而无需有人解释 Aggregate 的作用,因为我知道这里和互联网上的其他地方已经对此进行了深入介绍。当调用 Aggregate() 并使用类似的 linq 语句时

(a,b) => a+b

什么是a,什么是b?我知道 a 是当前元素,但是 b 是什么?我见过一些例子,其中 b 似乎只是 a 之前的一个元素,而其他例子中 a 似乎是前一个函数的结果,而其他例子看起来 b 是前一个函数的结果。

我已经在 http://msdn.microsoft.com/en-us/library/bb548744.aspx 和这里 http://www.dotnetperls.com/aggregate浏览了实际 C# 文档页面上的示例

但我只需要澄清一下 linq 表达式中两个参数之间的区别。如果我缺少一些基本的 Linq 知识来回答这个问题,请随时把我放在我的位置上。

4

3 回答 3

5

看看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 

在此示例中,传递给的匿名函数Aggregate(workingSentence, next) => next + " " + workingSentence. a将是workingSentence包含聚合结果直到当前元素,并且b将是当前元素被添加到聚合中。在第一次调用匿名函数时,workingSentence = ""next = "the". 在下一次通话中,workingSentence = "the"next = "quick"

于 2013-03-13T18:59:51.367 回答
4

如果您调用的重载采用与该描述匹配的 Func,则您很可能使用此版本:

可枚举.聚合

这意味着这a将是您的累加器,并且b将是下一个要使用的元素。

someEnumerable.Aggregate((a,b) => a & b);

如果您要将其扩展为常规循环,它可能类似于:

Sometype a = null;

foreach(var b in someEnumerable)
{
    if(a == null)
    {
        a = b;
    }
    else
    {
        a = a & b;
    }
}

将执行按位与并将结果存储回累加器。

于 2013-03-13T18:57:15.680 回答
3

a不是当前元素 -b是。第一次调用 lambda 表达式时,a将等于seed您提供给的参数Aggregate。以后的每一次,它都等于上一次调用 lambda 表达式的结果。

于 2013-03-13T18:58:34.493 回答