C# Sort list Box by Date in list entry Name

602 views Asked by At

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

one Item looks like:

DATA_department_08-09-2017.pdf

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.

2

There are 2 answers

5
Tim Schmelter On BEST ANSWER

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

If you want last dates first use OrderByDescending.

0
jhen On

The filenames are just strings but you could try to parse the filename into a custom class with a datetime field and the filename as property. You have to cut the date part from the filename and parse it into a real datetime type

Then you can use linq to order the list of files like mentioned here https://stackoverflow.com/a/5813530/4318778