Well, maybe you should use a Dictionary<DayOfWeek, TimeSpan?>
instead of multiple properties.
If that's not possible:
The efficient way, a switch
:
public class Deadlines
{
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; }
public TimeSpan? GetDeadLine(DayOfWeek dow)
{
switch(dow)
{
case DayOfWeek.Monday:
return Monday;
case DayOfWeek.Tuesday:
return Tuesday;
case DayOfWeek.Wednesday:
return Wednesday;
case DayOfWeek.Thursday:
return Thursday;
case DayOfWeek.Friday:
return Friday;
case DayOfWeek.Saturday:
return Saturday;
case DayOfWeek.Sunday:
return Sunday;
default: throw new ArgumentException(nameof(dow));
}
}
}
Or you could have a dictionary that returns the deadline:
public class Deadlines
{
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; }
private static readonly Dictionary<DayOfWeek, Func<Deadlines, System.TimeSpan?>> DayOfWeekMapper;
static Deadlines()
{
DayOfWeekMapper = new Dictionary<System.DayOfWeek, Func<Deadlines, System.TimeSpan?>>
{
{ DayOfWeek.Monday, dl => dl.Monday },{ DayOfWeek.Tuesday, dl => dl.Tuesday },{ DayOfWeek.Wednesday, dl => dl.Wednesday },
{ DayOfWeek.Thursday, dl => dl.Thursday },{ DayOfWeek.Friday, dl => dl.Friday },{ DayOfWeek.Saturday, dl => dl.Saturday },{ DayOfWeek.Sunday, dl => dl.Sunday }
};
}
public TimeSpan? GetDeadline(DayOfWeek dow) => DayOfWeekMapper[dow].Invoke(this);
}
There's also reflection but i would not use it here since it's not efficient and not readable.
Well, here it is:
public class Deadlines
{
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; }
private static readonly Dictionary<string,PropertyInfo> DayOfWeekPropertyMapper;
static Deadlines()
{
DayOfWeekPropertyMapper = typeof(Deadlines).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => Enum.GetNames(typeof(DayOfWeek)).Contains(p.Name))
.ToDictionary(p => p.Name, p => p);
}
public TimeSpan? GetDeadline(string dayOfWeek) => (TimeSpan?)DayOfWeekPropertyMapper[dayOfWeek].GetValue(this);
}
With your sample:
string dow = DateTime.Now.DayOfWeek.ToString();
IEnumerable<TimeSpan?> deadlines = _api.Select(x => x.Deadlines.GetDeadline(dow));