如果不使用一些可怕的循环/计数器类型解决方案,我甚至不确定如何做到这一点.这是问题所在:
我有两个日期,开始日期和结束日期,在指定的时间间隔内我需要采取一些行动.例如:对于2009年10月3日之间的每个日期,每隔三天至2009年3月26日,我需要在列表中创建一个条目.所以我的意见是:
DateTime StartDate = "3/10/2009";
DateTime EndDate = "3/26/2009";
int DayInterval = 3;
Run Code Online (Sandbox Code Playgroud)
我的输出将是一个具有以下日期的列表:
2009年3月13日3/16/2009 3/19/2009 3/22/2009 3/25/2009
那么我怎么会这样做呢?我想过使用一个for循环,它会在范围内的每一天之间迭代,使用一个单独的计数器,如下所示:
int count = 0;
for(int i = 0; i < n; i++)
{
count++;
if(count >= DayInterval)
{
//take action
count = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
但似乎可能有更好的方法?
如何获得给定月份的每个“星期一”日?
一个例子;
输入:2017年7
月
11日(2017年7月11日)输出:( 3,10,17,24,31)3.7.2017星期一
10.7.2017星期一
17.7.2017星期一
24.7.2017星期一
31.7.2017
我可以得到给定月份的天数(对于2017年7月为31天)。然后,如果dayOfWeek等于星期一,则编写一个迭代(用于循环AE),然后添加到列表中。但这不是很好的代码,因为for循环将工作31次。应该有一个更好的算法来归档目标。
我正在使用C#.net Framework 4.6
更新
感谢大家的帮助,到目前为止,我已经给出了一些答案。我使用简单且肮脏的基准代码测试了所有代码,以找到更快的算法。
这是我的基准代码;
using System;
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Columns;
using BenchmarkDotNet.Attributes.Jobs;
using BenchmarkDotNet.Engines;
using X.Core.Helpers;
namespace X.ConsoleBenchmark
{
[SimpleJob(RunStrategy.ColdStart, targetCount: 5)]
[MinColumn, MaxColumn, MeanColumn, MedianColumn]
public class LoopTest
{
[Benchmark]
public void CalculateNextSalaryDateWithLoopAllDays()
{
DateTime date = new DateTime(2017, 7, 3);
const int oneMillion = 1000000;
for (int i = 0; i < oneMillion; i++)
{
List<DateTime> allXDaysInMonth = date.GetAllXDaysInMonthWithLoopAllDays(DayOfWeek.Tuesday);
if (allXDaysInMonth …Run Code Online (Sandbox Code Playgroud)