C# for循环-高分数组
所以我试图做一个循环,遍历highscore arrayscorelist的每个索引,检查当前ScorePlayerCore是否高于当前索引。如果If语句得到yes,那么它应该将所有分数向下推还是更高?沿着索引,将playerScore放在应该的位置C# for循环-高分数组,c#,for-loop,C#,For Loop,所以我试图做一个循环,遍历highscore arrayscorelist的每个索引,检查当前ScorePlayerCore是否高于当前索引。如果If语句得到yes,那么它应该将所有分数向下推还是更高?沿着索引,将playerScore放在应该的位置 { Console.Write("input name: "); string playerName = Console.ReadLine(); Console.Write("input score: "); int
{
Console.Write("input name: ");
string playerName = Console.ReadLine();
Console.Write("input score: ");
int playerScore = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < 10; i++)
{
if (playerScore > scoreList[i])
{
int nextNo = 9;
for (int n = 10; n > 0; n--)
{
scoreList[n] = scoreList[nextNo];
nameList[n] = nameList[nextNo];
nextNo--;
}
scoreList[i] = playerScore;
nameList[i] = playerName;
}
}
}
在当前代码中,如果playerScore高于先前存储的索引,它只会将playerScore放在第一个索引上,然后沿索引的其余部分复制它。有关如何修复此问题的任何建议?将数组更改为列表并使用以下代码:
var scorelist = new List<int>();
//populate your scorelist;
var playerScore = someintValue;
var firstlower = scorelist.FirstOrDefault(x => x < playerScore);
if (firstlower != null)
scorelist.Insert(playerScore, scoreList.IndexOf(firstlower);
else
scorelist.add(playerScore);
编辑:
如果插入后需要将列表裁剪到最多10项,只需:
scorelist=scorelist.Take10.ToList 将数组更改为列表并使用以下代码:
var scorelist = new List<int>();
//populate your scorelist;
var playerScore = someintValue;
var firstlower = scorelist.FirstOrDefault(x => x < playerScore);
if (firstlower != null)
scorelist.Insert(playerScore, scoreList.IndexOf(firstlower);
else
scorelist.add(playerScore);
编辑:
如果插入后需要将列表裁剪到最多10项,只需:
scorelist=scorelist.Take10.ToList 这样做容易得多:
int prev = playerScore;
for (int i = 0; i < 10; i++)
{
if (playerScore > scoreList[i])
{
int temp = scoreList[i];
scoreList[i] = prev;
prev = temp;
}
}
我假设,您只需要前10个结果,而您的数组中已经有10个元素。可以更轻松地完成:
int prev = playerScore;
for (int i = 0; i < 10; i++)
{
if (playerScore > scoreList[i])
{
int temp = scoreList[i];
scoreList[i] = prev;
prev = temp;
}
}
我假设,您只需要前10个结果,并且您的数组中已经有10个元素。如果我得到的结果正确,您希望以从低分到高分的排序数组结束吗?在运行循环时,尝试添加一些断点并检查数组中的值。你应该很快解决这个问题。你是在尝试按分数排序吗?正如Roee所建议的:使用一个列表,然后对它进行排序。如果我得到的是正确的,你希望以一个从低分到高分的排序数组结束吗?试着在运行循环时添加一些断点并检查数组中的值。你应该很快解决这个问题。你是否在尝试按分数排序。正如Roee建议的那样:使用一个列表,然后对其进行排序。作为一个附带评论,随着的出现,对于在列表或数组中查找内容,for循环非常不受欢迎。很好,但是如何将列表限制为10分呢?@Steve,这到底是什么意思?是否要在插入新项后裁剪列表?是的,现在的答案是考虑到OP@HighCore:List.FindPredicate match和Array.FindT Array[],谓词匹配自.Net 2以来一直存在,所以有人可能会说,在列表和数组中查找内容的循环被弃用的时间甚至比Linq出现的时间还要长!作为旁白,随着的出现,for循环在查找列表或数组中的内容时几乎不受欢迎。很好,但是如何将列表限制为10分?@Steve,你的确切意思是什么?是否要在插入新项后裁剪列表?是的,现在的答案是考虑到OP@HighCore:List.FindPredicate match和Array.FindT Array[],谓词匹配自.Net 2以来一直存在,所以有人可能会说,在列表和数组中查找内容的循环被弃用的时间甚至比Linq出现的时间还要长!谢谢这就是我想做的。谢谢。这就是我想做的。