簡體   English   中英

如何根據所說字符串中的數字重新組織字符串列表?

[英]How can I reorganize a list of strings based on a number inside of said string?

我正在嘗試為我正在制作的地理測驗應用程序創建一個記分板。 我試圖按最大到最小的順序組織分數,我什至不知道從哪里開始。 這是提交按鈕功能的代碼:

    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] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41" ,並且該scoredouble numCorrect數,而numCorrectint (您不顯示它們的來源),那么這是處理這種情況的一種方法。

首先,使用要存儲的屬性創建一個類,該類具有從字符串(文件行)創建其自身的實例並將其自身輸出為字符串(用於寫入文件)的能力:

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

現在,該文件包含其原始內容以及表單中的新結果,所有結果均按Score排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM