【问题标题】:Sort listBox by date string c#按日期字符串对listBox排序c#
【发布时间】:2016-08-07 07:15:22
【问题描述】:

我正在尝试按日期对列表框项目进行排序,但不确定如何执行此操作。我已经设法使用正则表达式创建了一个包含日期的字符串,但我不确定如何使用这个字符串对 listBox 进行排序。任何建议将不胜感激。请参阅下面的代码。

DirectoryInfo dir = new DirectoryInfo("../Debug/");
FileInfo[] files = dir.GetFiles("*.txt");

foreach (FileInfo file in files)
{
    string dueDate = File.ReadAllText(file.Name);

    Regex regex = new Regex(@"\d{2}/\d{2}/\d{4}");
    Match mat = regex.Match(dueDate);

    string duedate = mat.ToString();//string containing date
    listBox1.Items.Add(file);
}

【问题讨论】:

  • 您想从哪里读取日期?文件名还是文件内容?
  • @JonnyAppleseed 注意您在file.Name 上使用ReadAllText,因为file.Name 将只返回其名称,而不是路径。所以要么是用户ReadAllText(file),要么如果你想要名字本身string dueDate = file.Name
  • 如果您为您的项目使用一个类(正如我对您的其他问题所建议的那样),您可以添加一个日期属性并在创建实例时填充它。这可以用于排序。就目前而言,您似乎在不知道自己在哪里以及想去哪里的情况下跳过问题。提示:您很可能想要切换到 ListView。
  • @RezaAghaei 字母顺序不适用于日期

标签: c# winforms visual-studio listbox


【解决方案1】:

这就是我的处理方式:

DirectoryInfo dir = new DirectoryInfo(@"../Debug/");
FileInfo[] files = dir.GetFiles("*.txt");
Dictionary<FileInfo, DateTime> filesWithDueDate = new Dictionary<FileInfo, DateTime>();

foreach (FileInfo file in files)
{
    string dueDate = File.ReadAllText(file.FullName);

    Regex regex = new Regex(@"\d{2}/\d{2}/\d{4}");
    Match mat = regex.Match(dueDate);

    DateTime duedate = Convert.ToDateTime(mat.ToString());

    filesWithDueDate.Add(file, duedate);
}

var sortedFiles = filesWithDueDate.OrderBy(a => a.Value).Select(b => b.Key.Name).ToArray();

listBox1.Items.AddRange(sortedFiles);

【讨论】:

  • 谢谢@jarednaszler。几乎可以工作,不幸的是它已经用每个项目的多个实例填充了列表框.....
  • @JonnyAppleseed - 它将列出该文件夹中每个文件的一项。您只需要唯一的截止日期还是其他什么?
  • 接收“字符串未被识别为有效的日期时间。” “DateTime duedate = Convert.ToDateTime(mat.ToString());”的错误..任何想法...在您的帮助下,我确实让它完美地工作...
  • 您的每个日期都必须是 00/00/0000。如果您有任何一位数的日期 (12/3/2016)、月份 (4/15/2016) 日期、两位数的年份 (04/15/16) 或上述任意组合,则您的 RegEx 将不匹配。您可以在调用regex.Match() 后检查mat.Success == true 属性。如果不匹配,您将不会在列表框中看到该文件。
  • @JonnyAppleseed - 你得到这个工作了吗?如果不是,让我们结束这个问题并接受答案。否则,让我知道什么仍然无法正常工作,我们可以解决。
猜你喜欢
  • 2014-02-01
  • 2021-12-18
  • 2018-07-07
  • 1970-01-01
  • 2021-07-05
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多