我有一个SortedDictionary,其中我持有一个特定球员的分数和他的名字旁边。我需要做的是按降序对它进行排序,这样我就可以在字典的第一个位置找到获胜者。我该怎么做呢?
另外,我如何在不知道密钥的情况下从列表中获取项?
SortedDictionary<int, string> dict = new SortedDictionary<int, string>();
dict.Add(player1Pts, playerNames[0]);
dict.Add(player2Pts, playerNames[1]);
dict.Add(player3Pts, playerNames[2]);谢谢你的帮助!
发布于 2012-12-06 18:19:55
将分数作为关键字使用字典是没有意义的:关键字必须是唯一的,所以如果两个玩家具有相同的分数,那么它将失败。
相反,您应该创建一个包含名称和分数的Player类,并将Player对象存储在List<Player>中。如果您需要按分数对球员进行排序,您可以使用自定义比较器调用列表上的Sort,或者只使用Linq对结果进行排序:
foreach (Player player in players.OrderByDescending(p => p.Score))
{
// Do something with player
}发布于 2012-12-06 18:28:42
首先:当您插入另一个值时,排序后的字典将始终立即排序。
但是请注意:使用积分作为关键意味着你不能让玩家拥有相同的分数。
但如果你想这样做,你可以简单地使用你的字典的Last()方法来获得积分最多的玩家:
SortedDictionary<int, String> t = new SortedDictionary<int,string>();
t.Add(5, "a");
t.Add(10, "c");
t.Add(2, "b");
MessageBox.Show((t.Last<KeyValuePair<int,string>>()).Value);这将导致"c“。
发布于 2012-12-06 18:21:28
首先,我认为你应该交换<int, string>播放器名称的位置应该是关键,而分数将是值。
然后您可以按值对其进行排序:
dict.Sort(
delegate(KeyValuePair<int, double> val1,
KeyValuePair<int, double> val2)
{
return val1.Value.CompareTo(val2.Value);
}
);您可以通过foreach遍历字典来获取键和值:
foreach (var pair in asd)
{
string some = pair.Key;
int someValue = pair.Value;
}https://stackoverflow.com/questions/13741314
复制相似问题