从系列结束日期范围linq获取每周的开始和结束日期 [英] Get every week's start and end date from series end date range linq
本文介绍了从系列结束日期范围linq获取每周的开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,用户将提供输入 StartDate
, EndDate
和 SeriesEndDate
。示例:
I have an application where a user will give input StartDate
, EndDate
and SeriesEndDate
. Example:
StartDate= 02/12/2019
EndDate = 03/16/2019
SeriesEndDate= 12/31/2025
我希望在 SeriesEndDate
中的所有期间的结果集中获取每周的开始和结束日期。但我希望这些周落在 SeriesEndDate
我尝试过的事情:
我使用下面的代码,但需要系列属于系列结束日期
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();
推荐答案
你的意思是这样的事情吗?
You mean somethig like this?
//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
仅限Linq方法:
With Linq methods only:
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();
这篇关于从系列结束日期范围linq获取每周的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文