2

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?

Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
NFI78
  • 43
  • 1
  • 10
  • Do they contain strings, or actual DateTime objects? – ryanyuyu Apr 03 '15 at 13:06
  • Just Strings. E.g. the word 'Monday' or 'Friday', etc. – NFI78 Apr 03 '15 at 13:06
  • 2
    Ok. Well the problem is that the sorting methods are treating them as just strings, so they are sorted alphabetically. You need to turn them into actual days of the week (which is an enum ( a number)). Then the sorts will work correctly. – ryanyuyu Apr 03 '15 at 13:08
  • How exactly do I do that? I'm quite new to programming. Sorry. – NFI78 Apr 03 '15 at 13:10
  • Take a look here about how to convert all elements in an array: https://msdn.microsoft.com/en-us/library/exc45z53(v=vs.100).aspx you could use this to convert to days of the week. – sr28 Apr 03 '15 at 13:15
  • Here's an example: http://stackoverflow.com/questions/4484127/sort-by-day-of-week – sr28 Apr 03 '15 at 13:16

2 Answers2

3

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() ; 
Perfect28
  • 11,089
  • 3
  • 25
  • 45
2

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.

Community
  • 1
  • 1
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53