Linq Select and Aggregate within a single iteration

aggregate, c#, linq

Solution

Yes, you can use the Enumerable.Aggregate method:

var result = fooCollection.Aggregate(new FooResult(),
                                    (r,f) => 
                                    { 
                                        r.SelectedIds.Add(f.Id);
                                        r.Content += f.Content;
                                        return r;
                                    });

This has the benefit of being side-effect free. I dislike side effects in my LINQ. =)

Problem

Is there a way to do this with linq without enumerating the `fooCollection` twice? ``` var fooCollection = // get foo var selectedIds = new List<int>(); var aggregateContent = String.Empty; foreach (var f in foo) { selectedIds.Add(foo.Id); aggregateContent += foo.Content } var results = new FooResults { Content = aggregateContent, SelectedIds = selectedIds }; return results; ```

Original source