C#在列表条目名称中按日期对列表框进行排序 [英] C# Sort list Box by Date in list entry Name

查看:85
本文介绍了C#在列表条目名称中按日期对列表框进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由DirectoryInfo填充的ListBox:

I have a ListBox, filled by 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

DATA_department_08-09-2017.pdf

所以我的问题是如何按日期末尾对列表框中的主题进行排序?我知道ListBox有一些排序功能,但对我不起作用.

So my Question is how to sort the Itmes in the ListBox by the Date at the end? I know there are some sort-functions for the ListBox but they don´t work for me.

推荐答案

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

So the file-name contains three tokens and the last is the date, you can use this LINQ approach:

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);

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

If you want to reorder the list-items without reading from file-system:

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 .

If you want last dates first use OrderByDescending.

这篇关于C#在列表条目名称中按日期对列表框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆