简体   繁体   中英

Sort a list consisting of strings made up of strings and integers

so I have a list in C# made up of strings that are made up of strings and integers. For example, 'Jim:50' or 'Ben:27'. I want to be able to sort this list using the integer, but I don't know where to start. My current code:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

public class Leaderboard : MonoBehaviour {

    string path = "Assets/Statistics.json";

    public List<string> scoresList = new List<string>();

    void Start() {
        JSONUnpacker();
        scoresList.Sort(scoreSorter);
    }

    void JSONUnpacker() {
        // Read from json file
        string jsonData = File.ReadAllText(path);
        leaderboard leaderboard = JsonUtility.FromJson<leaderboard>(jsonData);
        foreach(var i in leaderboard.statDataList) {
            // Repeat for every stat record
            string temp = i.username + ":" + i.score;
            scoresList.Add(temp);
        }
    }

    [System.Serializable]
    public class leaderboardData {

        public string username;
        public int score;
    }

    private class leaderboard {

        public List<leaderboardData> statDataList = new List<leaderboardData>();
    }
}

Any help is appreciated, thanks!

You need to get the number string and turn it into integer. For example if you are guaranteed to have format "letters" + ":" + "numbers" you can do something like that:

List<string> scoresList = new List<string>{"Jim:50","Ben:27", "John:28"};
var sorted = scoresList 
    .OrderBy(s => int.Parse(s.Substring(s.IndexOf(":") + 1)))
    .ToList();

You must sort by property, not only Sort Eg l.OrderBy(s => s.score) Also you could implement IComparable interface and.Sort will be working You could do it like

public class UserScore: IComparable<UserScore>
{
    public int Score {get; set;}

    public int CompareTo(UserScore other)
    {
        return Score.CompareTo(other.Score);
    }
}

It looks like you are creating the list yourself, and then you want to sort it. I'd recommend doing the sorting before/as you are creating the list, which thanks to LINQ OrderBy() can be done very easily:

foreach (var i in leaderboard.statDataList.OrderBy(x => x.score)) {
    // ...
}

Or if you need the opposite sort order, use OrderByDescending() :

foreach (var i in leaderboard.statDataList.OrderByDescending(x => x.score)) {
    // ...
}

To use Sort you need to write a "comparer" class.

to compare leaderboardData write this:

 public class leaderboardDataComparer : IComparer<leaderboardData>

and use Quick Actions (Ctrl+.) to implement missing method.

 public int Compare([AllowNull] leaderboardData x, [AllowNull] leaderboardData y)
 {
 }

Then write your comparison logic:

 if (x.score > y.score) return 1;
 if (x.score < y.score) return -1;
 return 0;

to compare string data, write this:

public class leaderboardStringDataComparer : IComparer<string>
{
     public int Compare([AllowNull] string x, [AllowNull] string y)
     {
          var xscore = Convert.ToInt32(x.Split(':')[1]);
          var yscore = Convert.ToInt32(y.Split(':')[1]);
          if (xscore > yscore) return 1;
          if (xscore < yscore) return -1;
          return 0;
     }
}

usage:

 scoresList.Sort(new leaderboardStringDataComparer());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM