I have next very non-optimized code:
void Summarize(IEnumerable<Section> sections)
{
this.DateBegin = sections.Select(s => s.Date).Min();
this.DateEnd = sections.Select(s => s.Date).Max();
this.Income = sections.Where(s => s.IsIncome).Sum(r => r.Amount);
this.ExpenditureBank = sections.Where(s => s.IsExpenditureBank).Sum(r => r.Amount);
this.ExpenditureClient = sections.Where(s => s.IsExpenditureClient).Sum(r => r.Amount);
this.Expenditure = this.ExpenditureBank + this.ExpenditureClient;
}
How to rewrite such it using IEnumerable.Aggregate()
, if applicable?
my solution is very close to Codesleuth's but would first define a Summary Struct
Note that the struct would ideally be immutable.
How's that?
EDIT:
Ok, I've had a rethink, take a look:
Beware of errors if
sections
is empty.Sometimes a good old fashioned
foreach
loop is the best tool for the job. I think that's the case here otherwise you're either going to be enumerating the sections multiple times or have some very unreadable LINQ code.And although you probably know ahead of time that the sections parameter will be an array or collection or what not, it might be something that is very expensive to enumerate or something that doesn't yield consistent values between enumerations. IEnumerable can surprise you sometimes.