2016-04-15 123 views
1

我試圖按日期排序listBox項目,但不知道如何做到這一點。我已經設法創建一個字符串包含使用正則表達式的日期,但我不知道如何使用此字符串排序列表框。任何意見將不勝感激..請參閱下面我的代碼。按日期排序listBox字符串c#

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

你想去哪兒來讀取日期?文件名或文件內容? – C4u

+0

[按字母順序顯示ListBox中顯示的內容](http://stackoverflow.com/questions/33963484/showing-what-is-displayed-in-listbox-in-alphabetical-order) –

+0

@JonnyAppleseed保重你,在'file.Name'上使用'ReadAllText',它不能工作,因爲'file.Name'將只返回它的名字,而不是路徑。所以無論是用戶'ReadAllText(file)'還是你想要這個名字'字符串dueDate = file.Name'。 – C4u

回答

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

謝謝@jarednaszler。幾乎可以工作,不幸的是它已經填充了每個項目的多個實例的列表框..... – JonnyAppleseed

+0

@JonnyAppleseed - 它將列出該文件夾中每個文件的一個項目。你只需要獨特的截止日期或其他東西? – jaredbaszler

+0

接收「字符串未被識別爲有效的日期時間」。錯誤「DateTime duedate = Convert.ToDateTime(mat.ToString());」..任何想法......我確實讓你的幫助完美無缺地工作...... – JonnyAppleseed