Sorting a list and figuring out the index

大城市里の小女人 提交于 2020-01-06 04:32:08

问题


Basically I'm trying to get a "rankings" between 4 people. I have an array of player scores which contains the scores of each person such that person 1's score is at index 0, person 2's score is at index 1, etc... I want to obtain the index of the top scorer in the list and get the second, and the third, and the last.

My attempt at the solution: I made a list out of the array playerScores (I feel like it might not be necessary, but due to what I'm about to do, I didn't want to ruin the original scores) which contains the scores in order. And then, I find the max number in the list and get its index. Then I change the value to a negative value at that index. And then I redo the steps.

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;

I feel like I can do this in a much more efficient manner and as less messy as this code... Well, this is also assuming that negative is not a score a person can get. Is there any other way, to be more efficient than this? And what about if say we want to have negative scores?


回答1:


Using LINQ:

using System.Linq;

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

And then display the winner, for example:

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



回答2:


You can build a dictionary where a player is a key and score is a value:

Dictionary<Player int> playerToScore;

Now you may sort players as you want, but when you need to get or change its score you just do:

var playerScore = playerToScore[myPlayer];



回答3:


Try using a dictionary like this:

        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


来源:https://stackoverflow.com/questions/9338480/sorting-a-list-and-figuring-out-the-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!