C#在列表条目名称中按日期排序列表框
C# Sort list Box by Date in list entry Name
我有一个 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
所以我的问题是如何按末尾的日期对列表框中的 Itmes 进行排序?我知道 ListBox 有一些排序功能,但它们对我不起作用。
文件名只是字符串,但您可以尝试将文件名解析为自定义 class,其中包含日期时间字段和文件名 属性。您必须从文件名中删除日期部分并将其解析为真正的日期时间类型
然后你可以使用 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
。
我有一个 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
所以我的问题是如何按末尾的日期对列表框中的 Itmes 进行排序?我知道 ListBox 有一些排序功能,但它们对我不起作用。
文件名只是字符串,但您可以尝试将文件名解析为自定义 class,其中包含日期时间字段和文件名 属性。您必须从文件名中删除日期部分并将其解析为真正的日期时间类型
然后你可以使用 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
。