0

特定のプレーヤーのポイントとその横にある彼の名前を保持している SortedDictionary があります。私がする必要があるのは、これを降順で並べ替えて、辞書の最初の位置に勝者が来るようにすることです。どうやってやるの?

また、キーを知らずにリストからアイテムを取得するにはどうすればよいですか?

SortedDictionary<int, string> dict = new SortedDictionary<int, string>();
dict.Add(player1Pts, playerNames[0]);
dict.Add(player2Pts, playerNames[1]);
dict.Add(player3Pts, playerNames[2]);

助けてくれてありがとう!

4

5 に答える 5

6

スコアをキーとして辞書を使用するのはあまり意味がありません。キーは一意でなければならないため、2 人のプレイヤーが同じスコアを持っていると失敗します。

代わりにPlayer、名前とスコアを含むクラスを作成し、PlayerオブジェクトをList<Player>. プレーヤーをスコアで並べ替える必要がある場合はSort、カスタム比較子を使用してリストを呼び出すか、Linq を使用して結果を並べ替えることができます。

foreach (Player player in players.OrderByDescending(p => p.Score))
{
    // Do something with player
}
于 2012-12-06T10:19:54.570 に答える
1

First: A Sorted Dictionary will always be sorted immediately, when you insert another Value.

But note: Using the points as KEY means that you cannot have players with EQUAL points.

But if you want to go with that, you can simple use the Last() Method of your Dictionary to get the player with the most points:

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

This Will Result in "c".

于 2012-12-06T10:28:41.903 に答える
0

私の問題への答えはそれを必要とするかもしれない誰にとってもこれでした:)

Player player1 = new Player(playerNames[0], player1Pts);
Player player2 = new Player(playerNames[1], player2Pts);
Player player3 = new Player(playerNames[2], player3Pts);
Player player4 = new Player(playerNames[3], player4Pts);
Player player5 = new Player(playerNames[4], player5Pts);

List<Player> players = new List<Player>();

players.Add(player1);
players.Add(player2);
players.Add(player3);
players.Add(player4);
players.Add(player5);

var sortedPlayers = (from Player play in players
                     orderby play.Points descending
                     select play);

List<Player> sortPlay = (List<Player>)sortedPlayers.ToList();
于 2012-12-06T19:23:45.653 に答える
0

<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;
            }
于 2012-12-06T10:21:27.880 に答える