我一直在尝试根据当前日来计算下一个可用的日期,即如果今天是星期五,则在数组中搜索下一个最近的日期,例如数组值是1 [Monday],2 [Tuesday],4 [周四],6 [周六],那么我的第二天应该是周六。
这是我尝试过的
//Here i'll get days like 0, 2, 3, 4, 6 pattern, and i'm spliting them based on comma to get single-single day value in array of string
string[] GetDays = DayInWeek.Split(','); [Here day patterns will change everytime, based on user selection]
//Here i'm looping to take each day and get Enum Text based on Enum Value
foreach (string FirstDay in GetDays)
{
//Here i'm converting the string value into int and passing to DayOfWeek Enum to get respective day
DayOfWeek DayChoosen = ((DayOfWeek)(Convert.ToInt32(FirstDay)));
//Here i have my actual day for example Friday
DayOfWeek StartDay = "Friday";
//Here i need condition to find next available day in the foreach i.e., after Friday next value should be Saturday, or Sunday, Monday & so on until Friday==Friday
if (StartDay == DayChoosen)
{
//End foreach
}
}
正如我根据当前日期告诉我的那样,我应该找到下一个可用的日期,即如果星期五应搜索星期六,如果星期六不存在,则应搜索星期天,星期一,依此类推,直到星期五=星期五
最佳答案
您不需要使用foreach
进行所有这些操作。
您可以执行以下操作:
private int nextDay(string dayInWeek, int startDay)
{
int[] getDays = dayInWeek.Split(',').Select(int.Parse).ToArray();
return getDays.Where(d => d > startDay).Any()
? getDays.Where(d => d > startDay).Min()
: getDays.Min();
}
此算法检查一周中是否有某些天出现在您的数组中,并且在
startDay
之后。否则,它将输出一周中的第一天。例如,对于字符串“ 0、2、3、4、6”:
对于
startDay
0-输出2,因为它是大于0的最小整数对于
startDay
1-输出2对于
startDay
3-输出4对于
startDay
6,它找不到大于6的项目,并且输出最小值0对于字符串“ 5”(仅星期五):
对于
startDay
5、6-不查找大于5的项目,输出最小值(5)对于
startDay
0-4-输出5,这是大于0-4的最小值