如果每个月只重复一次,如何查找当天的菜单?

时间:2017-09-21 11:32:11

标签: vb.net

我想创建我的节目,让我每周的每一天都能看到不同的一餐,到目前为止,这就是我所拥有的

Dim dt as DateTime.Now
If dt.DayofWeek = DayofWeek.Monday then
    Textbox1.Text = "Steak with a cup of rice and Iced tea"
Elseif dt.DayofWeek = DayofWeek.Tuesday then
    Textbox1.Text = "Crabcorn soup and water"
    'and so on until i reach friday
End if

我如何在接下来的几个星期内做这些,但使用不同的菜单而不是重复我在星期一等吃的同一餐?但是下个月会再次重演?

1 个答案:

答案 0 :(得分:1)

您可以使用Dictionary(Of Tuple(Of Int32, DayofWeek), String),其中键是元组,第一项是周数,第二项是DayOfWeek

Dim monthlyMeals = New Dictionary(Of Tuple(Of Int32, DayofWeek), String) From 
    {  {Tuple.Create(1, DayOfWeek.Monday), "Steak with a cup of rice and Iced tea" }, {Tuple.Create(1, DayOfWeek.Tuesday), "Crabcorn soup and water" } }

当然你必须填写这本词典。然后你可以用这段代码找到今天的饭菜:

Dim day = Date.Today
Dim dayTuple = Tuple.Create(GetWeekNumberOfday(day), day.DayOfWeek)
Dim todayMeal As String = Nothing
Dim mealIsDefined As Boolean = monthlyMeals.TryGetValue(dayTuple, todayMeal)

您需要此方法来获取给定日期一个月内的周数:

Public Shared function GetWeekNumberOfDay(day as date)As Int32
    Dim dayOfWeekOfDay1 = new Date(day.Year, day.Month, 1).DayOfWeek
    dim offset = Math.Max(dayOfWeekOfDay1 - day.DayOfWeek, 0)
    Dim weekNumber As Integer = (day.Day - offset) \ 7 + 1
    Return weekNumber
End function

为您完成的其他任务:创建一个类Meal,它封装了它的Name和其他有用的属性,然后将其用作字典的值。覆盖ToString以返回Name