Jamie
Jamie

Reputation: 4960

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 

Upvotes: 3

Views: 1875

Answers (2)

Axiom255
Axiom255

Reputation: 1397

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);
    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 887449

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 

Upvotes: 3

Related Questions