1 回答
TA贡献1777条经验 获得超10个赞
我做了一些假设,因为您没有更新您的问题,但假设文件行包含格式为: 的行"Score: [score] ~[Name] -- Timer: [mm:ss] -- [numCorrect]/41",并且score是 adouble并且numCorrect是 an 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()));
}
}
现在文件包含它的原始内容,加上表单的新结果,全部按Score.
- 1 回答
- 0 关注
- 81 浏览
添加回答
举报