在字符串数组中查找下一个可用的日期 [英] Find next available day in an Array of string

查看:86
本文介绍了在字符串数组中查找下一个可用的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试根据当前日来计算下一个可用的日期,即如果今天是星期五,则在Array中搜索下一个最近的日期,例如Array的值是1 [Monday],2 [Tuesday ],4 [星期四],6 [星期六],那么我的第二天应该是星期六。

I've been trying to figure out how to take next available day based on Present day i.e., if today is Friday, then search in Array for the next nearest day like if Array values are 1[Monday], 2[Tuesday], 4[Thursday], 6[Saturday] then my next day should be Saturday.

这是我尝试过的

    //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
    }
}

我根据当日告诉我,我应该找到下一个可用的日子,即如果星期五我应该搜索星期六,如果星期六不在那儿,那么星期日,星期一等,直到星期五=星期五

As i told based on present Day i should find next available day i.e, if Friday i should search for Saturday, if Saturday is not there then Sunday, Monday and so on till Friday=Friday

推荐答案

您不需要使用 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 之后。否则,它将输出一周中的第一天。

This algorithm checks if there are any days of a week, which are presented in your array, and come after the startDay. Else, it outputs the first available day in a week.

例如,对于字符串 0、2、3、4、6:

For example, for a string "0, 2, 3, 4, 6":


  • for startDay 0-输出2,因为它是大于0的最小整数

  • for startDay 1-输出2

  • for startDay 3-输出4

  • 对于 startDay 6,它没有找到大于6的项目,并且输出最少0

  • for startDay 0 - output 2, as it is the minimal integer which is more than 0
  • for startDay 1 - outputs 2
  • for startDay 3 - output 4
  • for startDay 6 it finds no items, which are more than 6, and outputs minimum 0

对于字符串 5(仅周五):

For string "5" (Friday only):


  • for startDay 5,6-没有发现超过5的项目,输出最小值(5)

  • startDay 0-4-输出5,作为大于0-4的最小数字

  • for startDay 5, 6 - finds no items which are more than 5, output minimum (5)
  • for startDay 0-4 - outputs 5, as the minimum number which is greater than 0-4

这篇关于在字符串数组中查找下一个可用的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆