Model:
public class ServiceHours
{
public int Id { get; set; }
...
public TimeSpan? Monday { get; set; }
public TimeSpan? Tuesday { get; set; }
public TimeSpan? Wednesday { get; set; }
public TimeSpan? Thursday { get; set; }
public TimeSpan? Friday { get; set; }
public TimeSpan? Saturday { get; set; }
public TimeSpan? Sunday { get; set; }
}
I'm currently iterating through a list of "service hour" objects (they can hold an optional start time for 1 or multiple days of the week). I want to be able to dynamically grab the value that corresponds to the DayOfWeek
enum from a DateTime
object.
This works but isn't very elegant
var today = DateTime.Today.DayOfWeek;
foreach (var item in myItems)
{
var time = new TimeSpan?();
if (today == DayOfWeek.Monday)
time = item.Monday;
else if (today == DayOfWeek.Tuesday)
time = item.Tuesday;
else if (today == DayOfWeek.Wednesday)
time = item.Wednesday;
else if (today == DayOfWeek.Thursday)
time = item.Thursday;
else if (today == DayOfWeek.Friday)
time = item.Friday;
else if (today == DayOfWeek.Saturday)
time = item.Saturday;
else if (today == DayOfWeek.Sunday)
time = item.Sunday;
...
}
UPDATE: I ended up using reflection at the time, but this was a very poor, naive design to begin with and this question should've been posted to Code Review anyways - This question should be disregarded, just adding this notice in case any others come along. Thanks to those who attempted to help out regardless of the terrible question!