我打算为XNA游戏制作一个框架大厅(前5名高分),但我在弄清楚如何制作方面遇到了一些麻烦。我有AllPlayer.json文件来记录播放器的名称,另一个json文件记录了paler的详细信息,如名称,分数等。 文本文件是这样的:(图片)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";
}
我非常感谢答案!
谢谢!
答案 0 :(得分: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);