Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by order of the weekdays (as in a calendar week) instead of alphabetical order (in C#)?

I cannot work out how to sort the output from a query in an XML file in isolated storage by the day which is a value in the xml file.

By this I mean it will sort by the first letter(s) of the day, so it will return Friday as the first one (because of the "F" in it). But that is not what I want, instead they should be sorted by the order of the weekdays, i.e. monday, tuesday, wednesday, thursday, friday.

Is there any way I can convert a string which contains the day in text eg. "monday" to a DateTime to sort by?

The code I am using is like so:

 let obv = (string)query.Element("day")
 orderby obv 
 select new obv 
like image 601
Jamie Avatar asked Dec 02 '25 05:12

Jamie


2 Answers

You can sort by the value's index in the CultureInfo.CurrentCulture.DateFormat.DayNames array:

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 
like image 133
SLaks Avatar answered Dec 03 '25 18:12

SLaks


This allows you to sort by an arbitrary 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);
    }
}
like image 36
Colin Breame Avatar answered Dec 03 '25 18:12

Colin Breame



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!