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

C# 如何根据所述字符串中的数字重新组织字符串列表?,c#,arrays,visual-studio,sorting,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"

我正在尝试为我正在制作的地理测验应用程序创建记分板。我试图把分数从大到小进行组织,我甚至不知道从哪里开始。以下是提交按钮功能的代码:

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

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

我做了一些假设,因为您没有更新您的问题,但假设文件行包含以下格式的行:score:[score]~[Name]-Timer:[mm:ss]-[numCorrect]/41,这个分数是一个双精度,numCorrect是一个整数,你不知道它们来自哪里,那么这里有一种方法来处理这种情况

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

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";
    }
}
现在我们可以从文件内容和表单中填充这些类的列表。然后,我们可以在本例中要评分的任何字段上使用Linq对列表进行排序,并可以将排序后的列表写回文件:

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

现在,该文件包含其原始内容,以及表单中的新结果,所有结果都按分数排序。

分数变量从何处获取?以及它与每一行的关系如何?在您的示例中找不到它。请对数组进行排序。您需要添加自定义转换器或将数组转换为整数以获得数字排序。此外,如果该行不包含分数,则您需要从该行对分数进行子串或解析。每个数组位置包含整行信息,而不仅仅是分数行[1]包含分数:2~完成后键入名称-计时器:00:02-4/41我的示例行请使用文件中的示例行更新您的问题。似乎您可以通过创建一个类来保存数据而受益,该类可以从字符串文件行创建自身的实例,并将自身输出为字符串以写入文件。是行的格式:Score:[Score]~[Name]-Timer:[mm:ss]-[numCorrect]/41Yup!这很有效。抱歉没有更新。我最近工作很忙,没有时间。
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()));
    }
}