What's an algorithm to retrieve values for a week to date calculation [closed]
The algorithm needs to accept a date and then get values for each day from Monday until the date inputted.
Edit:
In a database I have values stored for every day of the week. I want to be able to accept a date parameter and then retrieve a list of values from Monday of the week that date parameter falls in until the date parameter. e.g 5th May 2011. Retrieve values for each day from Monday 2nd May upto Thursday 5th May.
static IEnumerable<DateTime> DaysFromMonday(DateTime d)
{
var diff = d.DayOfWeek - DayOfWeek.Monday;
var monday = d.AddDays(-diff).Date;
for (var day = monday; day < d; day = day.AddDays(1))
yield return day;
}
var DateInput = DateTime.Now;
var FromMondayToDate =
from dateindex in Enumerable.Range(-7, 7)
let TestDate = DateInput.AddDays(dateindex)
let Monday = DateInput.AddDays(-(int)DateInput.DayOfWeek + (int)DayOfWeek.Monday)
where TestDate >= Monday
select TestDate;
EDIT: Looking at your edit, my answer gets you part-way there. You now have a list of dates to retrieve values for. You now have to query the database, or ideally run the query above on the database either by writing equivilent SQL, or by using LINQ to SQL.
You can try this
public List<DateTime> CreateDateList(DateTime inputDate)
{
List<DateTime> mondayList = new List<DateTime>();
while(inputDate.DayOfWeek != DayOfWeek.Monday)
{
mondayList.Add(inputDate);
inputDate = inputDate.AddDays(-1);
}
return mondayList;
}
Depending you need to forward or backwards change the AddDays paramter
精彩评论