How to sort in order on weekdays (like in a calendar week) instead of alphabetical order (in C #)?

I cannot decide how to sort the output from the request in an XML file in isolated storage by day, which is the value in the XML file.

By this I mean that it will be sorted by the first letter of the day, so it will return on Friday as the first (due to the “F” in it). But this is not what I want, instead they should be sorted on weekdays, that is, on Monday, Tuesday, Wednesday, Thursday, Friday.

Is there any way to convert a string containing a day in the text, for example. Monday in DateTime to sort by?

The code I use looks like this:

 let obv = (string)query.Element("day")
 orderby obv 
 select new obv 
+3
source share
2 answers

You can sort by index of values ​​in an array CultureInfo.CurrentCulture.DateFormat.DayNames:

var daynames = Array.ConvertAll(
    CultureInfo.CurrentCulture.DateFormat.DayNames,
    d => d.ToUpperInvariant()
);

from ...
let obv = (string)query.Element("day")
orderby Array.IndexOf(daynames, obv.ToUpperInvariant())
select new obv 
+3
source

This allows you to sort by any day of the week:

public class DayOfWeekComparer : IComparer<DayOfWeek>
{
    public static int Rank(DayOfWeek firstDayOfWeek, DayOfWeek x)
    {
        return (int)x + (x < firstDayOfWeek ? 7 : 0);
    }

    public static int Compare(DayOfWeek firstDayOfWeek, DayOfWeek x, DayOfWeek y)
    {
        return Rank(firstDayOfWeek, x).CompareTo(Rank(firstDayOfWeek, y));
    }

    DayOfWeek firstDayOfWeek;

    public DayOfWeekComparer(DayOfWeek firstDayOfWeek)
    {
        this.firstDayOfWeek = firstDayOfWeek;
    }

    public int Compare(DayOfWeek x, DayOfWeek y)
    {
        return DayOfWeekComparer.Compare(this.firstDayOfWeek, x, y);
    }
}
0
source

Source: https://habr.com/ru/post/1781123/


All Articles