键是玩家的名字,值是记录(以秒为单位),其中有一个代码需要改进
我有一个文件,上面有播放器的名称和结果(它们以不同的形式编写),在这种形式上,这些数据记录在字典中,然后按等级分配5个最佳结果。
目标:从文件中删除
以下是我尝试执行的操作:
private static Dictionary<string, int> AllNames()
{
return File
.ReadLines(@"C:\Users\D205\Desktop\картинки\results.txt")
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(item => item.Split(' '))
.ToDictionary(items => items[0],
items => int.Parse(items[1]));
}
private void updateRatingLabels()
{
var tops = AllNames()
.OrderBy(pair => pair.Value)
.ThenBy(pair => pair.Key, StringComparer.Ordinal)
.Take(5)
.ToArray();
if (System.IO.File.ReadAllLines(@"C:\Users\D205\Desktop\картинки\results.txt").Length >5)
{
for (int i = 18; i <= 22; ++i)
Controls.Find($"label{i}", true).First().Text = "";
for (int i = 28; i <= 32; ++i)
Controls.Find($"label{i}", true).First().Text = "";
for (int i = 0; i < tops.Length; ++i)
{
Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}"; //Controls.Find($"label{i + 28}", true).First().Text = tops[i].Value.ToString();
// remove tops.key
}
for (...)
{
// set delete from file by key
// remove these items from the dictionary
}
}
答案 0 :(得分:1)
有很多方法可以实现...这是一种:
// @"C:\Users\D205\Desktop\картинки\results.txt"
private static String FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SomeFile.txt");
private static Dictionary<string, int> AllNames()
{
return File
.ReadLines(FileName)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(item => item.Split(' '))
.ToDictionary(items => items[0],
items => int.Parse(items[1]));
}
private static void WriteNames(Dictionary<string, int> AllNames)
{
var lines = AllNames
.Select(kvp => kvp.Key + " " + kvp.Value.ToString())
.ToArray();
File.WriteAllLines(FileName, lines);
}
private void button1_Click(object sender, EventArgs e)
{
var top5 = AllNames()
.OrderBy(pair => pair.Value)
.ThenBy(pair => pair.Key, StringComparer.Ordinal)
.Take(5);
var tops = top5.ToArray();
// ... your existing code to work with "tops" ...
// write out the new file
Dictionary<string, int> top5dict = new Dictionary<string, int>();
foreach(var pair in top5)
{
top5dict.Add(pair.Key, pair.Value);
}
WriteNames(top5dict);
}
答案 1 :(得分:0)
您必须使用删除项的字典中的数据执行File.WriteAllLines。因此,您只需要覆盖旧文件即可。