Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
I have an application where a user will give input StartDate, EndDate and SeriesEndDate. Example:
C#
StartDate= 02/12/2019
EndDate = 03/16/2019
SeriesEndDate= 12/31/2025

I want to get start and end date of every week in a result set for all the period within the SeriesEndDate. But I want the weeks to fall within the SeriesEndDate

What I have tried:

I am using the code below but need the series to fall within the Series End date
var dating22 = (from d in dates
           where d.DayOfWeek == DayOfWeek.Monday
           select new 
           { 
             StartWeekDate = d.DayOfWeek != DayOfWeek.Monday ? d.Date.PreviousOfWeek(DayOfWeek.Monday) : d.Date, 
             EndWeekDate = d.NextDayOfWeek(DayOfWeek.Sunday) 
           }).Distinct();
Posted
Updated 10-Feb-19 23:24pm
v3
Comments
Richard MacCutchan 11-Feb-19 4:15am    
Why is the SeriesEndDate not between the StartDate and EndDate values? And what is the content of the dates variable in your LINQ expression?

1 solution

You mean somethig like this?

C#
//define helper class
public class WeekStartEnd
{
    public DateTime Monday;
    public DateTime Sunday;
}

//usage:
DateTime StartDate = DateTime.Parse("02/12/2019");
DateTime EndDate = DateTime.Parse("03/16/2019");
DateTime SeriesEndDate= DateTime.Parse("12/31/2025");
//find first monday
DateTime firstMonday =  Enumerable.Range(0, 7)
    .SkipWhile(x => StartDate.AddDays(x).DayOfWeek != DayOfWeek.Monday)
    .Select(x => StartDate.AddDays(x))
    .First();
//get count of days
TimeSpan ts = (TimeSpan)(SeriesEndDate - firstMonday);
//create new list of WeekStartEnd class
List<WeekStartEnd> dates = new List<WeekStartEnd>();
//add dates to list
for(int i=0; i<ts.Days; i+=7)
{
        //if(firstMonday.AddDays(i+6)<SeriesEndDate) //uncomment this line if you would like to get last sunday before SeriesEndDate
    dates.Add(new WeekStartEnd(){Monday=firstMonday.AddDays(i), Sunday=firstMonday.AddDays(i+6)});
}


Result:
Monday              Sunday
2019-02-18 00:00:00 2019-02-24 00:00:00 
2019-02-25 00:00:00 2019-03-03 00:00:00 
2019-03-04 00:00:00 2019-03-10 00:00:00 
...  
2025-12-22 00:00:00 2025-12-28 00:00:00 
2025-12-29 00:00:00 2026-01-04 00:00:00 


[EDIT]

With Linq methods only:

C#
int w = ts.Days / 7;

List<WeekStartEnd> dates = Enumerable.Range(0,w)
    .Select(x=> new WeekStartEnd(){Monday=firstMonday.AddDays(x*7), Sunday=firstMonday.AddDays(x*7+6)})
    .ToList();
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900