如何根据所述字符串中的数字重新组织字符串列表?

我正在尝试为我正在制作的地理测验应用程序创建一个记分牌。我正在尝试从最大到最小来组织分数,我什至不知道从哪里开始。下面是提交按钮功能的代码:


    private void button1_Click(object sender, EventArgs e)//Submit Button

    {

        if(isDone)

        {

            string[] lines = System.IO.File.ReadAllLines(path+"/score.txt");

            StreamWriter sw = new StreamWriter(path+"/score.txt");

            foreach (string line in lines)

            {

                if (line != null && line.Length > 0) {sw.WriteLine("\n"+ line); }

            }

            sw.WriteLine("Score:" + score +" ~"+ textBox1.Text + " -- " + label9.Text + " -- " + numCorrect + "/41" );

            sw.Close();

        }

    }

我想按分数变量和从文本文件中的行中获取的数字对其进行排序


富国沪深
浏览 82回答 1
1回答

不负相思意

我做了一些假设,因为您没有更新您的问题,但假设文件行包含格式为: 的行"Score: [score] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41",并且score是 adouble并且numCorrect是 an int(您没有显示它们来自哪里),那么这里是处理这种情况的一种方法。首先,使用要存储的属性创建一个类,该类能够从字符串(文件行)创建自身的实例并将自身输出为字符串(用于写入文件):private class Result{&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public double Score { get; set; }&nbsp; &nbsp; public TimeSpan Time { get; set; }&nbsp; &nbsp; public int CorrectCount { get; set; }&nbsp; &nbsp; /// <summary>&nbsp; &nbsp; /// Returns an instance of the Result class based on a string.&nbsp; &nbsp; /// The string must be in the format:&nbsp; &nbsp; /// "Score: [score] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41"&nbsp; &nbsp; /// Where [score] is a valid double and [numCorrect] a valid int&nbsp; &nbsp; /// </summary>&nbsp; &nbsp; /// <param name="input">The string to parse</param>&nbsp; &nbsp; /// <returns>A Result with properties set from the input string</returns>&nbsp; &nbsp; public static Result Parse(string input)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (input == null) throw new ArgumentNullException(nameof(input));&nbsp; &nbsp; &nbsp; &nbsp; var splitStrings = new[] {"Score:", " ~", " -- ", "/41"};&nbsp; &nbsp; &nbsp; &nbsp; var parts = input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Split(splitStrings, StringSplitOptions.RemoveEmptyEntries)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(item => item.Trim())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToList();&nbsp; &nbsp; &nbsp; &nbsp; // These will hold the converted parts of the string&nbsp; &nbsp; &nbsp; &nbsp; double score;&nbsp; &nbsp; &nbsp; &nbsp; int correctCount;&nbsp; &nbsp; &nbsp; &nbsp; TimeSpan time;&nbsp; &nbsp; &nbsp; &nbsp; // Verify that the string contains 4 parts, and that the Score, Time, and&nbsp; &nbsp; &nbsp; &nbsp; // CorrectCount parts can be converted to the proper data type for the property&nbsp; &nbsp; &nbsp; &nbsp; if (parts.Count != 4 ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; !double.TryParse(parts[0], out score) ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; !TimeSpan.TryParseExact(parts[2], @"mm\:ss",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CultureInfo.InvariantCulture, out time) ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; !int.TryParse(parts[3], out correctCount))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new FormatException("input is not in a recognized format");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new Result&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = parts[1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Score = score,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Time = time,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CorrectCount = correctCount&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; }&nbsp; &nbsp; public override string ToString()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $"Score:{Score} ~{Name} -- {Time.ToString(@"mm\:ss")} -- {CorrectCount}/41";&nbsp; &nbsp; }}然后创建一个可以从表单数据创建此类实例的方法:// Not sure where these come from so created these class fieldsprivate const string Path = @"f:\public\temp\score.txt";private double score = 0;private int numCorrect = 0;private static Result GetResultFromFormData(){&nbsp; &nbsp; return new Result&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Score = score,&nbsp; &nbsp; &nbsp; &nbsp; Name = textBox1.Text,&nbsp; &nbsp; &nbsp; &nbsp; Time = TimeSpan.ParseExact(label9.Text, @"mm\:ss", CultureInfo.InvariantCulture),&nbsp; &nbsp; &nbsp; &nbsp; CorrectCount = numCorrect)&nbsp; &nbsp; };}现在我们可以从文件内容和表单中填充这些类的列表。然后我们可以使用Linq我们想要的任何字段对列表进行排序(Score在这种情况下),并将排序后的列表写回文件:private void button1_Click(object sender, EventArgs e)//Submit Button{&nbsp; &nbsp; if (isDone)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Create a list of results from our file&nbsp; &nbsp; &nbsp; &nbsp; List<Result> existingResults = File.ReadAllLines(Path).Select(Result.Parse).ToList();&nbsp; &nbsp; &nbsp; &nbsp; // Add a new result to the list from the form data&nbsp; &nbsp; &nbsp; &nbsp; existingResults.Add(GetResultFromFormData());&nbsp; &nbsp; &nbsp; &nbsp; // Sort the list on the Score property&nbsp; &nbsp; &nbsp; &nbsp; existingResults = existingResults.OrderBy(result => result.Score).ToList();&nbsp; &nbsp; &nbsp; &nbsp; // Write the sorted list back to the file&nbsp; &nbsp; &nbsp; &nbsp; File.WriteAllLines(Path, existingResults.Select(result => result.ToString()));&nbsp; &nbsp; }}现在文件包含它的原始内容,加上表单的新结果,全部按Score.
打开App,查看更多内容
随时随地看视频慕课网APP