2012-02-18 8 views
0

基本的に私は4人の間で「ランキング」を取得しようとしています。私は、人1のスコアがインデックス0にあり、人2のスコアがインデックス1にあるというように、各人のスコアを含むプレイヤースコアの配列を持っています。リスト内のトップスコアラーのインデックスを取得したいと思います。第2、第3、そして最後を得る。リストをソートしてインデックスを見つける

解決方法: 私は配列の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

+1

listOfScores.Sort()はスコアを並べ替えますが、以前のインデックスを追跡しません。 – skyjlv

答えて

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 
関連する問題