Reputation: 332
public class Results
{
public DateTime Date {get; set;}
public decimal Result {get; set;}
}
public class Sums
{
public decimal YearlySum {get; set;}
public decimal MonthlySum {get; set;}
public DateTime Date {get; set;}
}
I have a collection of Results object.
I want to populate Sums list with Yearly, Monthly sums based on date.
YearlySum is the sum of all Results' values in the provided date's year (until the provided date), and MonthlySum is the sum of Results' values in the provided date's month (until the provided date)
How to do it using Linq?
Upvotes: 1
Views: 824
Reputation: 23174
Something like this function should do the work :
public Sum GetSumFromResultsAndDate(IEnumerable<Results> results, DateTime date) {
return new Sum {
Date = date,
MonthlySum = results
.Where(r => r.Date.Year == date.Year && r.Date.Month == date.Month && r.Date <= date)
.Sum(r => r.Value) ,
YearlySum = results
.Where(r => r.Date.Year == date.Year && r.Date <= date)
.Sum(r => r.Value)
}
}
(make the sum of all Result which have the same month and year than provided date for monthly sum, and sum of all results which have the same year as the provided date for the yearly sum)
EDIT : added the "result date inferior to provided date" condition as per question clarification
Upvotes: 1