For each loop through DayOfWeek enum to start on Monday?

Oliver picture Oliver · Jun 28, 2013 · Viewed 19.9k times · Source

I am iterating through the DayOfWeek Enum like this :

foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)))
{
 // Add stuff to a list 
}

And my problem is that I would like my enum to start by Monday instead of Sunday.

I tried to do :

CultureInfo ci = Thread.CurrentThread.CurrentCulture;
ci.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Monday;

But the foreach loop still started with Sunday.

How can I do this ?

My last idea would be to reorder my resulting list to the order of day I want but that would mean more iterations.

Thanks !

Answer

Simon Whitehead picture Simon Whitehead · Jun 28, 2013

That isn't possible, purely because setting the culture doesn't change the fact that the DayOfWeek enum is defined as such:

public enum DayOfWeek {
    Sunday = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 3,
    Thursday = 4,
    Friday = 5,
    Saturday = 6,
}

You can, however, skip the first entry and add it later.. perhaps like this:

foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek))
                              .OfType<DayOfWeek>()
                              .ToList()
                              .Skip(1)) {
    list.Add(day.ToString());
}
list.Add(DayOfWeek.Sunday.ToString());