[英]Sort txt file with JSON
I'm making a Scoreboard for a game. 我正在为游戏制作记分板。 I'm developing but have no experience with json. 我正在开发,但没有json经验。 So far I have made it so it adds a name with a score into a plain text file and also displaying this in game. 到目前为止,我已经做到了,因此它将带有分数的名称添加到纯文本文件中,并在游戏中显示该名称。 Now I want to sort it so that the name with the lowest score goes to the top. 现在,我想对它进行排序,以使得分最低的名称排在顶部。
Here is my code: 这是我的代码:
[WebMethod]
public static void Score(String gamescore, string loginname)
{
List<Highscore> Myhighscores = new List<Highscore>();
string hs = File.ReadAllText(@"c:\temp\hs.txt");
Myhighscores = JsonConvert.DeserializeObject<List<Highscore>>(hs);
Myhighscores.Add(new Highscore { Score = gamescore, Name = loginname });
string Jstr = JsonConvert.SerializeObject(Myhighscores);
File.WriteAllText(@"c:\temp\hs.txt", Jstr);
}
public void displayScore()
{
using (StreamReader r = new StreamReader(@"c:\temp\hs.txt"))
{
string json = r.ReadToEnd();
List<Highscore> items = JsonConvert.DeserializeObject<List<Highscore>>(json);
foreach (Highscore score in items)
{
lblHighscore.Text += $"{score.Name} > {score.Score} {"Turns"}<br/>";
}
}
}
I have tried a lot of things but nothing seems to be working. 我尝试了很多事情,但似乎没有任何效果。 Does anyone know how I can achieve this? 有谁知道我怎么能做到这一点?
ps Highscore contains 2 public strings called Name
and Score
. ps Highscore包含2个名为Name
和Score
公共字符串。
您需要先对对象进行排序,然后再将其写回到文件中。
Myhighscores.Sort((x, y) => string.Compare(x.Score, y.Score));
我需要做的很简单的就是将gamescore
更改为int
并添加以下代码:
List<Highscore> SortedList = items.OrderBy(o => o.Score).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.