2012-02-18 39 views
0

基本上我试图得到4人之间的“排名”。我有一系列球员得分,其中包含每个人的得分,例如人1的得分是在索引0,人2的得分是在索引1等等。我想获得列表中最高得分手的索引,以及获得第二个,第三个和最后一个。对列表进行排序并找出索引

我在解决方案的尝试: 我列出了阵列playerScores(我觉得它可能没有必要,但由于我要做的事情,我不想毁掉原来的分数),其中包含顺序的分数。然后,我找到列表中的最大数字并获得它的索引。然后我将该值更改为该索引处的负值。然后我重做这些步骤。

List<int> listOfScores = new List<int>(playerScores.ToList()); 
// We get the max value to determine the top scorer of the game 
// and then we insert a negative value at that same spot of the list so we can 
// continue on figuring out the following max value in the list, etc. 
rank1 = listOfScores.IndexOf(listOfScores.Max()); 
listOfScores[rank1] = -1; 

rank2 = listOfScores.IndexOf(listOfScores.Max()); 
listOfScores[rank2] = -1; 

rank3 = listOfScores.IndexOf(listOfScores.Max()); 
listOfScores[rank3] = -1; 

rank4 = listOfScores.IndexOf(listOfScores.Max()); 
listOfScores[rank4] = -1; 

我觉得我可以在一个更有效的方式和更少的凌乱这个代码做到这一点... 嘛,这也是假设负不是分数的人可以得到的。有没有其他办法,比这更有效率?如果说我们想要负分数呢?

+0

为什么你就不能使用listOfScores.Sort(); ? http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx – ccKep 2012-02-18 04:23:36

+1

listOfScores.Sort()会按顺序排列分数,但不会跟踪其先前的索引。 – skyjlv 2012-02-18 04:47:03

回答

0

使用LINQ:

using System.Linq; 

var ranked = playerScores.Select((score, index) => 
           new {Player=index+1, Score=score}) 
         .OrderByDescending(pair => pair.Score) 
         .ToList(); 

,然后显示赢家,例如:

Console.WriteLine(String.Format("Winner: Player {0} with score {1}", 
        ranked[0].Player, ranked[0].Score)); 
0

您可以构建一个字典,其中一名球员是一个关键和得分值:

Dictionary<Player int> playerToScore;

现在,只要你想,你可以排序的球员,但是当你需要获得或更改其分数您只是做:使用字典这样

var playerScore = playerToScore[myPlayer]; 
0

尝试:

 var userScores = new Dictionary<int,int>{{1,3},{2,2},{3,1},{4,6}}; 
     var orderedUserScores = userScores.OrderBy(x => x.Value); 
     //orderedUserScores[0] returns KeyValuePair of {3,1} 
     //So, the key is the player number/position, and the value is the score 
相关问题