Search Unity

Question Sorting player stats with two conditions

Discussion in 'Scripting' started by TimNick151297, May 19, 2021.

  1. TimNick151297

    TimNick151297

    Joined:
    Apr 21, 2013
    Posts:
    21
    Hi there,

    I'm trying to rank players (1st, 2nd, 3rd, ...). The players can have diamonds and coins, which are currently stored in two different arrays. How would I sort these two arrays, so that coins are less important than diamonds, but if a player has diamonds and coins, the player with the most diamonds AND coins will be first? All other players would be ranked in descending order.

    Thanks for any help, it is much appreciated!

    Cheers Tim
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    358
    I have this variant, this is the first stuff that was in my mind. I'm not sure how to translate this into two arrays, I'm not sure is it even possible to make one sort dependant on another. But you can just make some class like PlayerData which will contain the info and create an array of this PlayerData.
    Code (CSharp):
    1.  
    2. var playersData = new PlayerData[diamonds.Length];
    3.  
    4. for(int i = 0; i < diamonds.Length; i++)
    5. {
    6.     var data = playersData[i];
    7.     data.Diamonds = diamonds[i];
    8.     data.Coins = coins[i]
    9. }
    10.  
    11. var ordered = from data in playersData
    12.                     orderby data.Diamonds descending,
    13.                         data.Coins descending
    14.                     select data;
     
    Last edited: May 19, 2021
    TimNick151297 likes this.
  3. TimNick151297

    TimNick151297

    Joined:
    Apr 21, 2013
    Posts:
    21
    Thanks for your answer! Could not replicate your solution to 100%, but you gave me an idea and I solved it a bit differently:

    Code (CSharp):
    1. IEnumerable < Player > query = players.OrderByDescending(Player => Player.Diamonds).ThenByDescending(Player => Player.Coins);
    2.  
    3.         foreach (Player player in query)
    4.         {
    5.             Debug.Log(player.Diamonds+"// "+player.Coins);
    6.         }
     
    Lekret likes this.