2017-08-04 23 views
0

我有以下視圖模型:LINQ的排序字符串,日期時間

public class MvcFormsViewModel 
{ 
    public int RecCount { get; set; } 
    public List<Dictionary<string, string>> PageOfRecords { get; set; } 

    public MvcFormsViewModel() 
    { 
     PageOfRecords = new List<Dictionary<string, string>>(); 
    } 
} 

我控制器排序與數據如下:

vm.PageOfRecords = vm.PageOfRecords.OrderBy(x => x.ContainsKey(sortValue) ? x[sortValue] : 
                  string.Empty).Skip(startIndex).Take(endIndex - startIndex).ToList(); 

的sortValue被傳遞到控制器從視圖 - 它將成爲其中一列的名稱 - 也是字典中的一個關鍵字。

我的問題是,有時「sortValue」參數的值是一個時間戳,在這種情況下,我希望linq排序爲日期時間而不是字符串。我怎麼能這樣做?

+0

將字符串轉換爲'DateTime'將是最明顯的方式。 – Fabio

+2

用''yyyyMMddHHmmssffffff''重新格式化'DateTime'(只有在需要秒秒的情況下''f =')=>自動「正確」排序。 – Corak

+0

謝謝,但我該如何重新格式化?我想我必須改變傳遞給OrderBy方法的內容,但我不知道是什麼。 –

回答

1

喜歡的東西:

vm.PageOfRecords = vm.PageOfRecords 
    .Skip(startIndex) 
    .Take(endIndex - startIndex) 
    .OrderBy(x => x.ContainsKey(sortValue) ? DateTime.Parse(x[sortValue]) : DateTime.Min).ToList(); 

但可能涉及很多鑄造的,如果數據集較大。正如有人建議,如果數據類型已經是DateTime,這將使事情變得更容易