[英]Merge sort days of week in order of weekday and not alphabetical
I have an object array with a string property that represents the weekdays. 我有一个带有字符串属性的对象数组,该字符串表示工作日。 I want to write a merge sort algorithm to sort my object array in order of weekdays.
我想编写一种合并排序算法,以按工作日顺序对我的对象数组进行排序。
I am capable of writing a merge sort algorithm but I am wondering how I could get it to sort it in order of weekdays and not by alphabet? 我有能力编写合并排序算法,但是我想知道如何让它按工作日的顺序而不是按字母排序? Thanks very much in advance.
首先十分感谢。
Use a collection for the objects that supports custom comparators, or just implement IComparable on your object as demonstrated here . 为支持自定义比较器的对象使用一个集合,或者仅在您的对象上实现IComparable, 如此处所示 。 Then just use a static map of your property to an ordering or if you can map your string property to the DayOfWeek enum then use that built-in ordering.
然后,只需使用属性的静态映射到顺序即可;如果可以将字符串属性映射到DayOfWeek枚举,则可以使用该内置顺序。
Don't write the sort algorithem, instead, write a simple Comparer that will implement IComparer, convert your array to a list , sort that list, and then convert back to an array if needed. 不要编写排序算法,而是编写一个将实现IComparer的简单比较器,将数组转换为列表,对该列表进行排序,然后根据需要转换回数组。 a Possible comparer will be something like that:
一个可能的比较器将是这样的:
Public WeekDayNameComparer<YourObject> : IComparer<yourObject>
{
private string[] WeekDays = {"sunday", "monday", ..."friday"}
public int Compare(YourObject x, YourObject y) {
return Array.indexOf(WeekDays, x.WeekDay).CompareTo(Array.indexOf(WeekDays, y.WeekDay));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.