This might be too primitive, but for my use case, I need to maintain an array in which two attributes are linked to each other... For example - If I want to do Score gathering... Then I need an array which has scores and corresponding player names as each element.

So, when I do Array.Sort(PlayerScorearray) I even need the playername to be sorted in the order so that if I want to know the player with lowest score, I just go for the first element and then go to the corresponding player name.. Is it possible to do it in a simpler way? My mind can't think of a simple way to do this.

Edit : I am using C# for scripts

  • 1
    \$\begingroup\$ Do you mean you have two separate arrays? One for the score value and the other for the player name? If so, you will surely be interested in this question Otherwise, the Sort method accepts an instance of a class implementing the IComparer interface, so you can define your own compare method see here \$\endgroup\$ – Hellium Oct 19 '17 at 16:48
  • \$\begingroup\$ For now, I was digging onto Dictionary which is way more complicated for a beginner like me, but... Wow! That double array might work well for me, I ll try it out once. Thanks! \$\endgroup\$ – NWishAll Oct 19 '17 at 16:52

Two ways to do this:

  1. Make a tuple type that combines both pieces of information

    public struct ScoreEntry { public string playerName; public float score; }

    Then you can sort them using a custom comparer, like so:

    Array.Sort(scoreEntries, (ScoreEntry a, ScoreEntry b) => { return a.score - b.score; } );

    Or, to be more concise, you can make your ScoreEntry implement IComparable so that the default Sort knows how to sort them without this helper. ;)

  2. You can use the Array.Sort overload that takes two arrays and sorts them in parallel:

    Array.Sort(scores, playerNames);

    (In my experience, this method is not very efficient, but your mileage may vary)

Both these strategies are easily found by reviewing the MSDN documentation on sorting or doing a simple Google search (sorting is a pretty bread-and-butter operation, so there's tons of information out there about how to tackle it) - so please don't neglect to do your own research.

| improve this answer | |
  • \$\begingroup\$ I never thought Array sort would have overload with key and item types... Looked into it... Solved my problem! \$\endgroup\$ – NWishAll Oct 19 '17 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.