Search Unity

Sort Integers With Double Value

Discussion in 'Scripting' started by Ceylan12, Sep 19, 2020.

  1. Ceylan12

    Ceylan12

    Joined:
    Dec 24, 2016
    Posts:
    113
    Hello, I'm sorting my integers with .Sort function with list but I want to compare other value if my integers is equal. How can I make it? Thank you.
     
  2. Munchy2007

    Munchy2007

    Joined:
    Jun 16, 2013
    Posts:
    1,735
    Assuming you're sorting a list of things that contain an int value and the other value you want to compare, you can use the sort version that takes a custom comparer.

    Example to sort by id, and if the ids are the same, it will then compare the score.

    Code (CSharp):
    1. public struct MyStruct
    2. {
    3.     public int id;
    4.     public int score;
    5. }
    6.  
    7. ListOfMyStructs.Sort( (MyStruct x, MyStruct y) => {
    8.  
    9.     var idResult = x.id.CompareTo(y.id);
    10.     if (idResult != 0)
    11.         return idResult;
    12.     else
    13.         return x.score.CompareTo(y.score);
    14. } );
    My example was typed up outside of the IDE so may contain typos.
     
    Last edited: Sep 19, 2020
  3. Ceylan12

    Ceylan12

    Joined:
    Dec 24, 2016
    Posts:
    113
    Thank you. It worked!!!
     
    Last edited: Sep 20, 2020