开发者

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开发者_JS百科, 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 


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 


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜