C# C按列表条目名称中的日期对列表框进行排序

C# C按列表条目名称中的日期对列表框进行排序,c#,sorting,listbox,directoryinfo,C#,Sorting,Listbox,Directoryinfo,我有一个列表框,由DirectoryInfo填写: FileInfo[] files = (new DirectoryInfo(Program.pathtofiles())).GetFiles(); for (int i = 0; i < (int)files.Length; i++) { FileInfo fileName = files[i]; this.ListBox.It

我有一个列表框,由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);
            }
其中一项看起来像:

数据部门08-09-2017.pdf


因此,我的问题是如何按照末尾的日期对列表框中的ITME进行排序?我知道ListBox有一些排序函数,但它们对我不起作用。

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


然后,您可以使用linq对此处提到的文件列表进行排序

因此文件名包含三个标记,最后一个标记是日期,您可以使用此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.EnumerateFilesProgram.pathtofiles.SelectPath=>new{Path,Name=Path.**GetFileNameWithoutExtension**Path}.Selectx=>new{x.Path,Date=DateTime.Parsex.Name.Split'.'.last}.OrderByx=>x.Date.Selectx=>x.Path;如何在没有扩展名的情况下获取文件名?@Scrober:该方法位于System.IO命名空间中的Path类中,只有google;-因此,您也可以在不使用System.IO:Name=System.IO.Path.GetFileName的情况下编写,而不使用OutExtensionPathKay,起初,我的Visual Basic没有发现这个命令,并且using System.IO.Path也不可用,但是使用System.IO.Path.GetFileName而不使用OutExtension时,一切都正常好的,有时结尾是08-09-20171,有时是DATA_08-09-20174.pdf这样的名称,所以我认为它不会准确地处理来自pas的所有内容,但是未来的一切谢谢Lot@Scrober:如果要忽略日期后的部件,可以将其删除:DateTime.Parsex.Name.Split[0]。Split“uu0”。Last