【问题标题】:Sort lines in a text file by value按值对文本文件中的行进行排序
【发布时间】:2021-08-25 04:10:07
【问题描述】:

我希望 WPF 应用程序节省时间类似于排名中的应用程序。时间和尝试次数不是列出的问题,但是当我想在文本文件中对其进行排序时会出现问题。用户将能够在文本文件中打开排行榜,并且当应用程序完成时,图表(文本文件)将打开并显示用户的时间。

 private void writeText(string strPath, TimeSpan tsDuration)
    {
        using (StreamWriter str = new StreamWriter(strPath, true))
        {
            str.WriteLine(tsDuration / suma);
            //duration= time of the game
          //suma= number of attempts
        }
    }
readonly string path = @"C:\Users\info\Desktop\žebříček.txt";
TimeSpan duration = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);//this is from other methods

图片显示为现在存储的样子:

但我希望它像这样存储,其他尝试按时间值排序:

每次应用程序完成时,用户的新时间应该按照它的速度排序。 我很乐意为您提供任何建议

谢谢

【问题讨论】:

  • 您的问题与 WPF 有什么关系? WPF 是一个 GUI 构建工具。如果您需要在 GUI 中显示排序列表,那么这将与 WPF 有关。但是您需要对文本文件的内容进行排序。它与 GUI 无关。
  • @EldHasp 因为应用程序是在WPF中创建的,所以写出来说明一下
  • 对于你的时间总是按顺序增加的情况,你需要将下一行写到文件的末尾而不是文件的开头。为此,您必须重写文件。或许在这里你会找到你需要的解决方案:stackoverflow.com/questions/12333892/…在随机时间计数的情况下,你必须将已经记录的信息完整读取,再补充一个新的,排序并重新编写。
  • @EldHasp 以下值由用户决定应用程序控制多快或多慢
  • 如果您需要在 WPF GUI 中查看已排序的行,那么无论这些行是如何写入文件中的,都可以解决此问题。但是要找到解决方案,我们需要您在 GUI 中与这些行的输出相关的代码。

标签: c# text streamwriter write


【解决方案1】:

我确信有很多更聪明的方法可以实现相同的结果,但一种非常简单的方法是:

  • 读取文件内容
  • 将内容分配给列表
  • 将您的值附加到列表中
  • 使用 linq 对列表进行相应的排序
  • 将列表写回文件

示例:

using System.Collections.Generic;
using System.IO;
using System.Linq;

private void WriteText(string strPath, TimeSpan tsDuration)
{
    //Create new list of type 'TimeSpan'
    var list = new List<TimeSpan>();

    //Read the contents of the file and assign to list
    string line;
    using (var sr = new StreamReader(strPath))
    {
        while ((line = sr.ReadLine()) != null)
        {
            list.Add(TimeSpan.Parse(line));
        }
    }

    //Add your time value to the list
    list.Add(tsDuration);

    //Order the list in descending order - use OrderBy for ascending
    list.OrderByDescending(i => i);

    //Write contents back to file - note: append = false
    using StreamWriter str = new StreamWriter(strPath, false);
    foreach (var item in list)
    {
        str.WriteLine(item);
    }
}

readonly string path = @"C:\Users\info\Desktop\žebříček.txt";
TimeSpan duration = TimeSpan.FromMilliseconds(mt.ElapsedMilliseconds);//this is from other methods

【讨论】:

  • 感谢您的建议,但您的代码总是删除其他时间,只留下最后一个
  • 抱歉 - 我已经修复了示例
猜你喜欢
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 2021-09-04
  • 2011-10-15
  • 2019-06-25
相关资源
最近更新 更多