NFI78
NFI78

Reputation: 63

How to sort an array of week days so that they appear as in a calendar week (in C#)?

I have a text file being read into a string[] containing the days Monday to Friday, but in a random order. I want to sort them so they appear as they do in a calendar week.

I've tried Array.Sort() and Array.Reverse() but they don't work.

Any ideas?

Upvotes: 4

Views: 3638

Answers (2)

Perfect28
Perfect28

Reputation: 11317

Just sort it by the corresponding value of enum DayOfWeek of your string, then return it back to a string.

string [] initialArray = {"Friday", "Monday", ... } ; 

string [] sortedArray = initialArray.OrderBy(s => Enum.Parse(typeof(DayOfWeek), s)).ToArray() ; 

Upvotes: 5

ryanyuyu
ryanyuyu

Reputation: 6486

Well the problem is that the sorting methods are treating them as just strings, so they are sorted alphabetically (the default comparison for strings). You need to turn them into actual days of the week (which is an enum ( a number)).

To convert into a DayOfWeek enum:

public static DayOfWeek ToDayOfWeek(string str) {
        return (DayOfWeek)Enum.Parse(typeof(DayOfWeek), str);
}

Then you can just sort them using the built-in functions.

I like LINQ:

String[] weekdayArray = {"Monday", "Saturday", "Wednesday", "Tuesday", "Monday", "Friday"};
var daysOfWeek = weekdayArray
    .Select(str => ToDayOfWeek(str))
    .OrderBy(dow => dow);

Here is a .NET Fiddle.

Upvotes: 2

Related Questions