[英]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. 我无法弄清楚如何在隔离存储中的XML文件中查询输出到xml文件中的值。
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). 我的意思是它将按当天的第一个字母排序,因此它将作为第一个字母返回星期五(因为它中的“F”)。 But that is not what I want, instead they should be sorted by the order of the weekdays, ie 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?
“星期一”到DateTime排序?
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: 您可以按
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
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.