2013-03-13 151 views
3

我想要用最好的方式来说出这个问题,以便我的确切问题不需要有人解释Aggregate做了什么,因为我知道这已经在互联网上的其他地方深入报道了。当调用Aggregate()并使用linq语句如什么是A&B代表.Aggregate((a,b)=>声明w/a&b)

(a,b) => a+b 

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

我已经通过实例看实际的C#文档页面这里 http://msdn.microsoft.com/en-us/library/bb548744.aspx 这里 http://www.dotnetperls.com/aggregate

但我只是需要一些澄清在LINQ表达式两个参数之间的差异。如果我错过了一些基本的Linq知识来回答这个问题,请随时把我放在我的位置。

+0

这取决于您打电话给哪个签名。 – SLaks 2013-03-13 18:55:36

+0

a和b是传递给Aggregate的lambda委托的参数。它们的类型(除非你得到编译器错误)由C#编译器推断,取决于上下文和被调用的具体扩展方法,并且可以通过将它们悬停在lambda的RHS上来确定它们的类型。 – 2013-03-13 18:57:31

回答

2

a不是当前元素 - b是。 lambda表达式第一次被调用时,a将等于您给Aggregateseed参数。随后的每个时间将等于先前调用lambda表达式的结果。

+0

所有的答案都是正确的,并帮助我理解发生了什么,但我觉得这是最简洁的。 – SmashCode 2013-03-13 21:51:45

3

如果你调用,需要一个Func键匹配描述过载,你最有可能使用这个版本:

Enumerable.Aggregate

这意味着,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; 
    } 
} 

会进行位和并将结果返回到累加器。

3

看一看的例子在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 + " " + workingSentencea将为workingSentence,其中包含到当前元素的聚合结果,b将被添加到聚合中。在匿名函数的第一个调用中,workingSentence = ""next = "the"。在下一个电话中,workingSentence = "the"next = "quick"

相关问题