简体   繁体   中英

Sort listBox by date string c#

I'm attempting to sort listBox Items by date, but not sure how to do this. I've managed to create a string that contains the date using Regex, but I'm not sure how to use this string to sort the listBox. Any advice would be appreciated.. Please see my code below.

DirectoryInfo dir = new DirectoryInfo("../Debug/");
FileInfo[] files = dir.GetFiles("*.txt");

foreach (FileInfo file in files)
{
    string dueDate = File.ReadAllText(file.Name);

    Regex regex = new Regex(@"\d{2}/\d{2}/\d{4}");
    Match mat = regex.Match(dueDate);

    string duedate = mat.ToString();//string containing date
    listBox1.Items.Add(file);
}

This is how I would approach it:

DirectoryInfo dir = new DirectoryInfo(@"../Debug/");
FileInfo[] files = dir.GetFiles("*.txt");
Dictionary<FileInfo, DateTime> filesWithDueDate = new Dictionary<FileInfo, DateTime>();

foreach (FileInfo file in files)
{
    string dueDate = File.ReadAllText(file.FullName);

    Regex regex = new Regex(@"\d{2}/\d{2}/\d{4}");
    Match mat = regex.Match(dueDate);

    DateTime duedate = Convert.ToDateTime(mat.ToString());

    filesWithDueDate.Add(file, duedate);
}

var sortedFiles = filesWithDueDate.OrderBy(a => a.Value).Select(b => b.Key.Name).ToArray();

listBox1.Items.AddRange(sortedFiles);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM