bolwire
bolwire

Reputation: 87

How can I use the return of .DayOfWeek to check property of class

I have a scheduler program which allows the user to choose which days of the week it will be allowed to run a schedule.

The properties in my class include each day of the week.

Instead of using 7 statments like if (Schedule[i].Sunday == true)

How would I go about something like this:

if (Schedule[i].(DateTime.Now.DayOfWeek) == true)

Upvotes: 0

Views: 424

Answers (4)

Jeremy Hutchinson
Jeremy Hutchinson

Reputation: 2045

It's tough to say without knowing the structure of your Schedule, but if you're storing a DayOfWeek type in your Schedule you can use this:

Schedule[i].DayOfWeek == DateTime.Today.DayOfWeek;

You could also get a list of scheduled items from your List like this

var scheduledItems = schedule.Where(x=>x.DayOfWeek == DateTime.Today.DayOfWeek)

Upvotes: 0

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12797

You can make int DaysOfWeek property in the class, which will have its bits set according to day of week. Let's say 0000001 - Sunday, 0000010 - Monday, 0000011 - Sunday & Monday. I start from Sunday, because DayOfWeek enum starts from Sunday (http://referencesource.microsoft.com/#mscorlib/system/dayofweek.cs). Then you can check the property the following way:

if ((DaysOfWeek & (1 << (int)DateTime.Now.DayOfWeek)) != 0)
{
}

Upvotes: 1

madrang
madrang

Reputation: 824

Make an enum with all day of the week set as flags,

[Flags]
Enum DaysOfWeek
{
None = 0,
Monday = 1 << 1,
Tuesday 1 << 2,
...
}

Then you will be able to use days.HasFlag(DaysOfWeek.Monday); to check for specific days. http://msdn.microsoft.com/en-us/library/system.enum.hasflag(v=vs.110).aspx

You can also use them in a switch statement to do different actions for each days.

Sadly the current C# system.dayofweek has values from 0 to 6 http://msdn.microsoft.com/en-us/library/system.dayofweek(v=vs.110).aspx so it doesn't work with HasFlag

Upvotes: 0

Gigi
Gigi

Reputation: 29421

You should use a multidimensional array for Schedule; your first index will be i, and your second one is the day of the week as an integer.

Then cast the DayOfWeek to an integer:

if (Schedule[i][((int)DateTime.Now.DayOfWeek)] == true)

Note that I'm using the DayOfWeek as the second index, rather than a property. This is why I mentioned using a multidimensional array earlier.

Upvotes: 0

Related Questions