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

时间:2019-01-15 21:04:49

标签: c# arrays visual-studio sorting

我正在尝试为我正在制作的地理测验应用创建记分板。我试图按最大到最小的顺序组织分数,我什至不知道从哪里开始。这是“提交”按钮功能的代码:

    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();
        }
    }

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

1 个答案:

答案 0 :(得分:1)

由于您尚未更新问题,因此我做出了一些假设,但假设文件行包含以下格式的行:"Score: [score] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41",并且score是{{1} },而doublenumCorrect(您不会显示它们的来源),那么这是处理这种情况的一种方法。

首先,使用要存储的属性创建一个类,该类具有从字符串(文件行)创建其自身的实例并将其自身输出为字符串(用于写入文件)的能力:

int

然后创建一个方法,该方法可以从您的表单数据创建此类的实例:

private class Result
{
    public string Name { get; set; }
    public double Score { get; set; }
    public TimeSpan Time { get; set; }
    public int CorrectCount { get; set; }

    /// <summary>
    /// Returns an instance of the Result class based on a string.
    /// The string must be in the format:
    /// "Score: [score] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41"
    /// Where [score] is a valid double and [numCorrect] a valid int
    /// </summary>
    /// <param name="input">The string to parse</param>
    /// <returns>A Result with properties set from the input string</returns>
    public static Result Parse(string input)
    {
        if (input == null) throw new ArgumentNullException(nameof(input));

        var splitStrings = new[] {"Score:", " ~", " -- ", "/41"};

        var parts = input
            .Split(splitStrings, StringSplitOptions.RemoveEmptyEntries)
            .Select(item => item.Trim())
            .ToList();

        // These will hold the converted parts of the string
        double score;
        int correctCount;
        TimeSpan time;

        // Verify that the string contains 4 parts, and that the Score, Time, and
        // CorrectCount parts can be converted to the proper data type for the property
        if (parts.Count != 4 ||
            !double.TryParse(parts[0], out score) ||
            !TimeSpan.TryParseExact(parts[2], @"mm\:ss", 
                CultureInfo.InvariantCulture, out time) ||
            !int.TryParse(parts[3], out correctCount))
        {
            throw new FormatException("input is not in a recognized format");
        }

        return new Result
        {
            Name = parts[1],
            Score = score,
            Time = time,
            CorrectCount = correctCount
        };
    }

    public override string ToString()
    {
        return $"Score:{Score} ~{Name} -- {Time.ToString(@"mm\:ss")} -- {CorrectCount}/41";
    }
}

现在,我们可以从文件内容和表单中填充这些类的列表。然后,我们可以在想要的任何字段上使用// Not sure where these come from so created these class fields private const string Path = @"f:\public\temp\score.txt"; private double score = 0; private int numCorrect = 0; private static Result GetResultFromFormData() { return new Result { Score = score, Name = textBox1.Text, Time = TimeSpan.ParseExact(label9.Text, @"mm\:ss", CultureInfo.InvariantCulture), CorrectCount = numCorrect) }; } 对列表进行排序(在这种情况下为Linq),并将排序后的列表写回到文件中:

Score

现在文件包含其原始内容,以及表单中的新结果,全部按private void button1_Click(object sender, EventArgs e)//Submit Button { if (isDone) { // Create a list of results from our file List<Result> existingResults = File.ReadAllLines(Path).Select(Result.Parse).ToList(); // Add a new result to the list from the form data existingResults.Add(GetResultFromFormData()); // Sort the list on the Score property existingResults = existingResults.OrderBy(result => result.Score).ToList(); // Write the sorted list back to the file File.WriteAllLines(Path, existingResults.Select(result => result.ToString())); } } 排序。