Skip to main content
 首页 » 编程设计

c#之排序高分的数组

2024年02月13日13飞鱼

我正在使用 C# 开发一个项目,该项目涉及跟踪剪刀石头布游戏的前五名高分。现在我有一个数组来保存前五个分数(整数),我按降序对数组进行排序,然后使用 for 循环将用户刚刚获得的分数与数组中当前的分数进行比较。如果新分数比数组中的分数高,那么现在新分数只占用数组中较低分数占据的空间。

例如,如果分数是 9、8、5、3、1,而用户得了 6 分,则分数将如下所示:9、8、6、3、1。我想知道是否有办法对我来说,将较低的分数移过来并插入新的分数,因此列表将如下所示:9、8、6、5、3。

这是我目前拥有的代码,其中 successPercent 是得分,计算方式为获胜除以失败和平局:

int[] scoreArray = { 84, 25, 36, 40, 50 }; 
 
Array.Sort(scoreArray); 
Array.Reverse(scoreArray); 
 
for (int x = 0; x <= scoreArray.Length; ++x) 
{ 
    if (successPercent > scoreArray[x]) 
    { 
        scoreArray[x] = Convert.ToInt32(successPercent); 
        break; 
    } 
} 

请您参考如下方法:

像这样的东西可以达到目的:

  • 创建临时列表
  • 添加新分数
  • 降序排列
  • 前 5 名...

    int[] scoreArray = { 84, 25, 36, 40, 50 }; 
     
    var tempList = new List<int>(scoreArray ); 
    int newScore = ...;//Get the new score 
    tempList.Add(newScore); 
     
    scoreArray = tempList.OrderByDescending(x=>x) 
                     .Take(5) 
                     .ToArray();