Linq Aggregate Function

I have a list like

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

But when I use Aggrate on it and at the same time I call the function, it seems to me that after 2 'iterations' the result of the first is passed to?

I use it like:

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

and when I put a breakpoint in the someMethod function, where some kind of conversion of information to myList takes place, I notice that after the third call I get the result from the previous conversion as an input parameter.

+1
source share
2 answers

The way it is designed to work.

What you designated as current means everything that has been accumulated so far. At the first call, the seed is the first element.

You can do something like:

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

This way you only apply someMethod once for each element.

+1
source

If my list was a list of strings, and I wanted to return / manipulate only certain elements, 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; }); 
0
source

Source: https://habr.com/ru/post/1387123/


All Articles