按日期字符串c#

时间:2016-04-15 10:45:38

标签: c# winforms visual-studio listbox

我试图按日期对listBox项目进行排序,但不确定如何执行此操作。我设法创建了一个包含使用Regex的日期的字符串,但我不确定如何使用此字符串对listBox进行排序。任何建议将不胜感激..请参阅下面的代码。

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

1 个答案:

答案 0 :(得分:0)

这就是我接近它的方式:

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