获取并返回3周范围内的特定日期列表的最佳选择是什么?
我的目的是根据交货中心给定的可用日期来创建交货日期
public List<DayOfWeek> DeliveryDays { get; set; }
DeliveryDays包含从0到6的设置值(0是星期日,1星期一等)
我想获取这些值,将它们传递给接下来的3周,然后返回列表中的交货日期(因此,只有那些中心可以在选定的日期订购)。
这是我到目前为止的内容:
public List<DateTime> CalculateAvailableDeliveryDates()
{
//Loop through 3 weeks of days
DateTime today = DateTime.Today; //Specify today's date
DateTime totalDateCount = today.AddDays(1); //Plus one day on each time counted
var dates = Enumerable.Range(0, 21).Select(days => totalDateCount.AddDays(days)).ToList(); //Count from 0 to 21 (3 weeks worth of days). On each count, run totalDateCount
//if exists in deliveryDayList
//add to dates via dates.Add func
if (DeliveryDays.Contains(DayOfWeek.Monday))
{
//action
} //and so on for each day
//return specific dates from date range
return dates;
}
目前,我的读数为21天。 if语句不执行任何操作,仅作为我的逻辑示例。
最好的方法是:不是先获取列表,而是根据每个中心的DeliveryDates进行检查和嵌套if / case语句,然后将它们返回到列表中?
提前感谢。
给出DayOfWeek
的列表,您可以使用21
选择接下来的System.Linq
天中与一周中的某一天匹配的所有日期。 Enumerable.Range
选择一个数字范围,Select
然后选择一堆DateTime
对象,它们代表Today
加一些天数,并且Where
用于过滤结果,比较DayOfWeek
每个日期以查看是否存在于DeliveryDays
中:
List<DayOfWeek> DeliveryDays = new List<DayOfWeek>();
public List<DateTime> GetAvailableDeliveryDates()
{
// 1. Get a range of numbers representing the days to add
// to today, which will make up our range of dates
// 2. Select a date using Today.AddDays for each number
// 3. Filter on only days which are contained in DeliveryDays
return Enumerable.Range(0, 21) // Define the range
.Select(i => DateTime.Today.AddDays(i)) // Select the range
.Where(date => DeliveryDays.Contains(date.DayOfWeek)) // Filter the range
.ToList();
}