我有一个对象数组(stockArray),它具有存储一周中几天的字符串属性。我已经完成了一个合并排序算法,按照一周的日期排序,而不是按字母顺序排序。我通过将天数转换为数字并将它们存储在double []数组中来完成此操作:
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;
}
}
}
然后我执行合并排序,现在我想将已经排序的值输出回一周格式的日期(即&#34;星期一&#34;,&#34;星期二&#34 ;等),并将一周中正确的日期与对象数组中的其他属性(stockArray)匹配
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循环中。它不会崩溃 - 只是简单地输出所有元素。所以,如果有人能帮我找到这段代码中的错误,我将不胜感激。
答案 0 :(得分:1)
试试这个解决方案:
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);
}