对列表进行排序并确定索引 [英] Sorting a list and figuring out the index

查看:179
本文介绍了对列表进行排序并确定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我试图在4人之间获得排名。我有一系列的球员得分,其中包含每个人的得分,使得人1的得分在索引0,人2的得分在索引1等等...我想获得列表中最佳得分手的索引,得到第二个,第三个,也就是最后一个。

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?

推荐答案

使用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));

这篇关于对列表进行排序并确定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆