1

我将为 XNA 游戏制作一个框架大厅(前 5 名高分),但我在弄清楚如何做时遇到了一些麻烦。我有一个 AllPlayer.json 文件来记录玩家的名字,另一个 json 文件记录了更苍白的细节,比如名字、分数等。文本文件是这样的:(图片)http://upic.me/i/zc/t56v1.jpg

现在我可以降序排序,但我只需要前 5 人

例子:

A 100 
B 50
C 30
D 10
E 45
F 55
G 90 

它应该是这样的:

A 100
G 90
F 55
B 50
E 45

代码:

List<List<string>> lst = new List<List<string>>();

  lst.Add(new List<string>());
  lst.Add(new List<string>());

for (int i = 0; i < ap.PlayerName.Count; i++)
{

detail = JsonBuilder.DeserializeFromFile<Player>("C:\\VirtualDrumGame\\Player\\" + ap.PlayerName[i] + ".json");

    lst[0].Add(detail.Score.ToString());
    lst[1].Add(detail.PlayerName);

}

 var myComparer = new CustomComparer();

lst[0].Sort((x, y) =>
{
 int ix, iy;
 return int.TryParse(x, out ix) && int.TryParse(y, out iy)
 ? ix.CompareTo(iy) : string.Compare(x, y);
});

 for (int j = lst[0].Count - 1; j <= lst[0].Count - 1; j--)
{

  temp += lst[1][j].ToString() + "  Score: " + lst[0][j].ToString() + "\n";
}

我真的很感谢答案!

谢谢!!

4

1 回答 1

0

也许简单的使用IEnumerable.Take(<number>)

var list = new List<int>(){1,3,2,6,9,2,3,5,4,8};
var result = list.OrderByDescending(p => p).Take(5).ToList();

或将其保留在您的示例中并使其更简单

var lst = new List<List<string>>()
{
    new List<string>(){"A","22"},
    new List<string>(){"B","7"},
    new List<string>(){"C","4"},
    new List<string>(){"D","3"},
    new List<string>(){"E","10"},
    new List<string>(){"F","5"},
    new List<string>(){"G","1"},
};

var result = lst.OrderByDescending(p=>Int32.Parse( p[1] )).Take(5);

哪个输出

Player A Score: 22
Player E Score: 10
Player B Score: 7
Player F Score: 5
Player C Score: 4

如果 int 无法解析,只是为了使排序更安全一点,您也可以使用

var outInt = 0;
var result = lst.OrderByDescending(p =>
            {
                if (Int32.TryParse(p[1], out outInt))
                {
                    return outInt;
                }
                else
                {
                    return -1;
                }
            }).Take(5);
于 2013-10-05T15:31:56.657 回答