2010-05-02 125 views
1

我有一個像的LINQ聚合函數

列表

「測試」,「喇嘛」,「東西」,「其他」

但是,當我使用Aggrate它,並在平均時間調用一個函數在我看來,經過2'迭代'的第一個結果傳入?

我使用它,如:

myList.Aggregate((current, next) => someMethod(current) + ", "+ someMethod(next)); 

,雖然我把一個斷點在上在myList中信息的某些轉變發生的someMethod功能,我注意到,第三個呼叫後,我得到的結果以前的轉換作爲輸入參數。

+5

我認不出什麼東西被要求在這裏;我建議你發佈你正在使用的代碼,並描述預期/實際結果。 – Aaronaught 2010-05-02 15:21:00

+0

@Aarounaught它不是那麼神祕(如果你使用了Aggregate),那麼我們只是將OP混淆在聚合函數的參數上 – eglasius 2010-05-04 18:50:10

+0

[LINQ Aggregate algorithm explain]的可能重複(http://stackoverflow.com/questions/7105505/LINQ聚集算法解釋的) – Jamiec 2015-10-05 14:49:16

回答

1

這就是其打算工作的方式。

你已經標記爲目前,它的意思是所有迄今已經積累的。在第一次調用時,種子是第一個元素。

你可以這樣做:

var res = myList 
    .Aggregate(String.Empty, (accumulated, next) => accumulated+ ", "+ someMethod(next)) 
    .Substring(2);//take out the first ", " 

這樣的話,你只能每個元素上應用的someMethod一次。

0

如果我的名單是一個字符串列表,我想回/僅操縱某些項目,我通常會做這樣的事情:

 var NewCollection = MyStringCollection 
          //filter with where clause 
          .Where(StringItem => StringItem == "xyz" 
          //select/manipulate with aggregate 
          .Aggregate(default(string.empty), (av, e) => 
          { 
           //do stuff 
           return av ?? e; 
          });