1

I have a List like

"test", "bla", "something", "else"

But when I use the Aggrate on it and in the mean time call a function it seems to me that after 2 'iterations' the result of the first gets passed in?

I am using it like :

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

and while I put a breakpoint in the someMethod function where some transformation on the information in the myList occurs, I notice that after the 3rd call I get a result from a former transformation as input paramter.

Nyla Pareska
  • 1,377
  • 6
  • 22
  • 37
  • 5
    I can't decipher what's being asked here; I suggest you post the code you're using and a description of what the expected/actual results were. – Aaronaught May 02 '10 at 15:21
  • @Aaronaught it isn't that cryptic (if u have used Aggregate), imo the OP is just confused over the parameters of the aggregate function – eglasius May 04 '10 at 18:50
  • Possible duplicate of [LINQ Aggregate algorithm explained](http://stackoverflow.com/questions/7105505/linq-aggregate-algorithm-explained) – Jamiec Oct 05 '15 at 14:49

2 Answers2

1

That's the way its intended to work.

What you have labeled current, its meant to be all that have been accumulated so far. On the first call, the seed is the first element.

You could do something like:

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

That way, you only apply someMethod once on each element.

eglasius
  • 35,831
  • 5
  • 65
  • 110
0

If my list was a list of strings, and i wanted to return/manipulate only certain items, I would usually do something like this:

     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;
                             });
Tresto
  • 151
  • 1
  • 12