簡體   English   中英

根據C#中的鍵對字典列表進行排序

[英]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));

我說這是一個糟糕的選擇,因為擁有字典列表似乎有點可濫用的模式,您可能應該擁有具有屬性NameDate的對象列表,其中Date屬性實際上是DateTime類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM