[英]Sorting a list of dictionary based on a key in C#
我有一個字典列表,我希望它按降序在日期鍵上排序。 但是以下查詢給出了不合適的結果。 請幫忙。
日期格式為DD / MM / YYYY
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
Dictionary<string, string> dict1 = new Dictionary<string, string>();
dict1["Date"] = "01/03/2015";
dict1["Name"] = "bbb";
list.Add(dict1);
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["Date"] = "11/08/2014";
dict2["Name"] = "ccc";
list.Add(dict2);
Dictionary<string, string> dict3 = new Dictionary<string, string>();
dict3["Date"] = "21/03/2014";
dict3["Name"] = "aaa";
list.Add(dict3);
Dictionary<string, string> dict4 = new Dictionary<string, string>();
dict4["Date"] = "01/01/2015";
dict4["Name"] = "ddd";
list.Add(dict4);
var ordered = list.OrderBy(x => x["Date"]);
每個詞典中的“ Date
條目都是一個字符串,“ List
對於如何根據日期排序規則對字符串進行排序一無所知。
一個(糟糕的)選擇是在訂購時將每個字符串轉換為適當的日期
var ordered = list.OrderBy(x => DateTime.ParseExact( x["Date"], "dd/MM/yyyy", CultureInfo.CurrentCulture));
我說這是一個糟糕的選擇,因為擁有字典列表似乎有點可濫用的模式,您可能應該擁有具有屬性Name
和Date
的對象列表,其中Date
屬性實際上是DateTime
類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.