【问题标题】:C# Sort list Box by Date in list entry NameC# 按列表条目名称中的日期对列表框进行排序
【发布时间】:2017-09-08 09:32:20
【问题描述】:

我有一个 ListBox,由 DirectoryInfo 填充:

FileInfo[] files = (new DirectoryInfo(Program.pathtofiles())).GetFiles();
            for (int i = 0; i < (int)files.Length; i++)
            {
                FileInfo fileName = files[i];
                this.ListBox.Items.Add(fileName);
            }

一个项目看起来像:

DATA_department_08-09-2017.pdf

所以我的问题是如何按最后的日期对 ListBox 中的 Itmes 进行排序?我知道 ListBox 有一些排序功能,但它们对我不起作用。

【问题讨论】:

    标签: c# sorting listbox directoryinfo


    【解决方案1】:

    所以文件名包含三个标记,最后一个是日期,您可以使用这种 LINQ 方法:

    var sortedPaths = Directory.EnumerateFiles(Program.pathtofiles())
        .Select(Path => new { Path, Name = Path.GetFileNameWithoutExtension(Path) })
        .Select(x => new { x.Path, Date = DateTime.Parse(x.Name.Split('_').Last()) })
        .OrderBy(x => x.Date)
        .Select(x => x.Path);
    

    如果您想重新排序列表项而不从文件系统中读取:

    var sortedPaths = this.ListBox.Items.Cast<string>()
        .Select(Path => new { Path, Name = Path.GetFileNameWithoutExtension(Path) })
        .Select(x => new { x.Path, Date = DateTime.Parse(x.Name.Split('_').Last()) })
        .OrderBy(x => x.Date)
        .Select(x => x.Path);
    this.ListBox.Items.AddRange(sortedPaths.ToArray());
    

    如果您想要最后日期,请先使用OrderByDescending

    【讨论】:

    • var sortedPaths = Directory.EnumerateFiles(Program.pathtofiles()) .Select(Path =&gt; new { Path, Name = Path.**GetFileNameWithoutExtension**(Path) }) .Select(x =&gt; new { x.Path, Date = DateTime.Parse(x.Name.Split('_').Last()) }) .OrderBy(x =&gt; x.Date) .Select(x =&gt; x.Path);如何获取没有Extentsion的文件名?
    • @Scrober: 该方法在Path-class 中,在System.IO 命名空间中,只是google ;-) 所以你也可以写(没有using System.IO):Name = System.IO.Path.GetFileNameWithoutExtension(Path)
    • 好的,起初我的 Visual Basic 没有找到这个命令,并且使用 System.IO.Path 也不可用,但使用 System.IO.Path.GetFileNameWithoutExtension 一切正常
    • 好吧,有时候结尾像“08-09-2017(1)”,有时会有一个像“DATA_08-09-2017(4).pdf”这样的名字,所以我认为它不会准确地处理过去的一切,但处理未来的一切。 :) 非常感谢
    • @Scrober:如果您想忽略日期之后的部分,可以将其删除:DateTime.Parse(x.Name.Split('(')[0].Split('_').Last())
    【解决方案2】:

    文件名只是字符串,但您可以尝试将文件名解析为具有日期时间字段和文件名作为属性的自定义类。您必须从文件名中删除日期部分并将其解析为真正的日期时间类型

    然后你可以使用 linq 来订购这里提到的文件列表https://stackoverflow.com/a/5813530/4318778

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2018-03-18
      • 2016-03-24
      • 1970-01-01
      相关资源
      最近更新 更多