1

so I have this dictionary

Dictionary<ulong, PlayerData> PlayersCache = new Dictionary<ulong, PlayerData>();

I have class PlayerData

        public class PlayerData
        {
            public int Shots;
            public int Hits;
            public PlayerData()
            {
            }
        }

How can I sort Dictionary so player with the most hits will be first the second player with most hits will be second, third player with most hits will be third... In the Dictionary Sort it ascending.

NotBad
  • 47
  • 6

3 Answers3

1

Using LINQ:

var ordered = PlayersCache.OrderByDescending(_ => _.Value.Hits);

You can add .ToList() or similar to end depending on how you wish to use it.

Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27
1

Add a value ID to the class:

public class PlayerData
{
    public ulong ID;
    public int Shots;
    public int Hits;
    public PlayerData()
    {
    }
}

The sorting:

Dictionary<ulong, PlayerData> PlayersCache = new Dictionary<ulong, PlayerData>();

// ... adding records to the dictionary

List<PlayerData> lst = new List<PlayerData>();
foreach (var kv in PlayersCache)
{
    lst.Add(kv.Value);
    kv.Value.ID = kv.Key;
}

lst.Sort(delegate (PlayerData x, PlayerData y) {
    return y.Hits.CompareTo(x.Hits);
});

PlayersCache.Clear();

foreach(var p in lst)
{
    PlayersCache.Add(p.ID, p);
}
mjb
  • 7,649
  • 8
  • 44
  • 60
  • and I read it normally from PlayersCache? foreach (var aPlayer in BasePlayer.activePlayerList) { if (PlayersCache.ContainsKey(aPlayer.userID)) { – NotBad Apr 20 '20 at 15:01
  • This part: `foreach (var aPlayer in BasePlayer.activePlayerList) { if (PlayersCache.ContainsKey(aPlayer.userID)) }` is not located in your code in your question. When do you execute this code? – mjb Apr 20 '20 at 15:04
  • I execute it to create UI Panel for each player etc... It is in UnityEngine – NotBad Apr 20 '20 at 15:06
  • It looks like that is not related to your question. Do you execute that before or after the sorting? – mjb Apr 20 '20 at 15:10
  • I execute it every 2 seconds Look https://imgur.com/qVyyaOu.png – NotBad Apr 20 '20 at 15:11
  • Anyway, your question is about sorting a dictionary and solution provided. If you just want to sort the list, then you don't actually need dictionary. You can sort the list without the dictionary. – mjb Apr 20 '20 at 15:14
  • First guy is always the one added first in PlayersCache I wanted to change the order in foreach – NotBad Apr 20 '20 at 15:25
0

Dictionaries are unsorted (though that are implementations that sort by key value). If you want to sort by values then don't use a dictionary - use either a List<Key, Value> as in this answer, or a sorted Lookup as provided in this answer

D Stanley
  • 149,601
  • 11
  • 178
  • 240