How can I manage to do something like this
` Heli Takedown >
playername | 10
playername | 19
playername | 23 etc.. `
I am storing the Player and damage done in a dictionary, just finding it hard to take it all out and then print it into a message and only print the top 5 players who did the most damage. Code:
private void SendHeliMessage()
{
foreach (KeyValuePair<BasePlayer, int> hitInfo in HeliHits)
{
BasePlayer Player = hitInfo.Key;
int DamageDone = hitInfo.Value;
var players = HeliHits.Keys;
SendMessage(Player,$"this is a test, Heli Takedown >\n\n{0} | {1}", null, 0, Player.displayName, string.Join("\n", DamageDone));
}
}
void SendMessage(BasePlayer player, string message, params object[] args)
{
PrintToChat(player, message, args);
}
(Yes i know what I have is wrong it was me just messing around and testing)
CodePudding user response:
To sort the dictionary by Value from highest to lowest may look something like…
var sorted = HeliHits.OrderByDescending(key => key.Value);
Then to loop through the dictionary and output all the Key Value pairs may look something like…
foreach (KeyValuePair<BasePlayer, int> hitInfo in sorted) {
SendMessage(hitInfo.Key, $"this is a test, Heli Takedown >\n\n{0} | {1}", hitInfo.Key.displayName, string.Join("\n", hitInfo.Value));
}
If you wanted only the top 5 values in the dictionary then you could do something like….
var sorted = HeliHits.OrderByDescending(key => key.Value).Take(5);
CodePudding user response:
Sorry for not seeing the obvious initially. A dictionary is by design unordered, but of course you can iterate over it in a ordered way by explicitly requesting an ordered enumeration:
private void SendHeliMessage()
{
foreach (KeyValuePair<BasePlayer, int> hitInfo in HeliHits.OrderByDescending(x => x.Value)) // Get players with their score ordered from the best to the worst
{
BasePlayer Player = hitInfo.Key;
int DamageDone = hitInfo.Value;
var players = HeliHits.Keys;
SendMessage(Player, $"this is a test, Heli Takedown >\n\n{0} | {1}", null, 0, Player.displayName, string.Join("\n", DamageDone));
}
}
To get a single message:
private void SendHeliMessage()
{
StringBuilder result = new StringBuilder();
int rank = 1;
foreach (KeyValuePair<BasePlayer, int> hitInfo in HeliHits.OrderByDescending(x => x.Value)) // Get players with their score ordered from the best to the worst
{
BasePlayer Player = hitInfo.Key;
int DamageDone = hitInfo.Value;
var players = HeliHits.Keys;
result.Append($"Rank {rank}: Player {Player.displayName} with {DamageDone} points");
rank ;
}
SendMessage(Player, result.ToString(), null, 0, Player.displayName, string.Empty);
}