Reputation: 127
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!
Upvotes: -1
Views: 154
Reputation: 793
If you are able to modify the class of the object
that makes up your objectList
variable, then try using a Dictionary<DayOfWeek, TimeSpan?>
in that class. DayOfWeek
would be the key
and TimeSpan?
would be the value
. This would simplify the class as well as eliminate the long if-else
logic.
Also, if I'm not mistaken, this method would also be faster than using reflection and wouldn't rely on the property names of your object
to be spelled exactly the same of the days of the week in DayOfWeek
(if you needed to refactor for some reason in the future).
Here is an example:
static void Main(string[] args)
{
List<WeekObject> weekObjs = new List<WeekObject>();
foreach (var obj in weekObjs)
{
SaveTime(obj.ID, obj.weekDictionary[DateTime.Today.DayOfWeek]);
}
}
class WeekObject
{
public int ID { get; set; }
public Dictionary<DayOfWeek, TimeSpan?> weekDictionary { get; set; } = new Dictionary<DayOfWeek, TimeSpan?>();
public WeekObject ()
{
// Initialize dictionary here if you'd like
weekDictionary.Add(DayOfWeek.Sunday, null);
}
}
public static void SaveTime(int ID, TimeSpan? timeSpan)
{
// Your code here
}
Upvotes: 1
Reputation: 62248
Something like this probably (did not compiled this code though)
object.GetType().GetProperty(today.DayOfWeek.ToSring()).GetValue(object)
use reflection to get property value,with only condition that DayOfWeek
enum member has to have exact name of the property present in object
type.
Upvotes: 0