Merge sorting days of the week
我有一个对象数组(stockarray),它具有存储一周中几天的字符串属性。我已经做了一个合并排序算法来按星期几而不是按字母顺序排序。我通过将天数转换为数字并将其存储在双[]数组中来完成此操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 | string[] daysArray = new string[5] {"Monday","Tuesday","Wednesday","Thursday","Friday" }; for (int i = 0; i < stockArray.Length; i++) //stockarray is the object array { for (int j = 0; j < daysArray.Length; j++) { if (daysArray[j] == stockArray[i].day) { sortArray[i] = j; break; } } } |
然后我执行合并排序,现在我想输出已经排序的值,返回到星期几格式(即"星期一"、"星期二"等),并将一周中的正确日期与对象数组(stockarray)中的其他属性相匹配。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | string day =""; int m = 0; while (m < stockArray.Length) { foreach (double a in sortArray) { if (a == 0) day ="Monday"; else if (a == 1) day ="Tuesday"; else if (a == 2) day ="Wednesday"; else if (a == 3) day ="Thursday"; else if (a == 4) day ="Friday"; if (day == stockArray[m].day) { Console.WriteLine(stockArray[m].date); Console.WriteLine(stockArray[m].day); Console.WriteLine(stockArray[m].open); Console.WriteLine(stockArray[m].close); Console.WriteLine(stockArray[m].difference); Console.WriteLine(stockArray[m].volume); Console.WriteLine(""); } m++; } } Console.ReadLine(); |
此代码的问题在于,它在stockarray中的144天中输出31天。我已经检查了合并排序算法代码,它似乎工作得很好,所以错误似乎出现在while和foreach循环中。它不会崩溃-只是不输出所有元素。因此,如果有人能帮我找出这段代码中的错误,我将不胜感激。
这个简单的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | class Stock { public int Value; public string Day; } Dictionary<string, int> dic = new Dictionary<string, int>(); dic.Add("Monday", 0); dic.Add("Tuesday", 1); dic.Add("Wednesday", 2); dic.Add("Thursday", 3); dic.Add("Friday", 4); var stocks = new Stock[] { new Stock { Day ="Tuesday", Value= 10 }, new Stock { Day ="Monday", Value= 5 }, }; // result here var result = stocks.OrderBy(f => dic[f.Day]).ToArray(); foreach (var item in result) { Console.WriteLine(item.Day); Console.WriteLine(item.Value); } |