[英]Sorting a List<Dictionary<string,string>> based on a specific keys value
我有一個 collections 的 Dictionary 對象。
例子:
List<Dictionary<string,string>> allData = new List<Dictionary<string,string>>();
我在每個 Dictionary object 中大約有 30 個條目,其中一個是保存為字符串的 DateTime。 我想根據特定鍵對字典對象列表進行排序,該特定鍵將 DateTime 字段按降序/升序保存為字符串。
示例數據:
Dictionary<string,string> temp = new Dictionary<string,string>();
temp.Add("Key1", "test1");
temp.Add("Key2", "6-12-2019-00:00:00");
// ...
temp.Add("KeyN", "1");
allData .Add(temp);
temp = new Dictionary<string,string>();
temp.Add("Key1", "test2");
temp.Add("Key2", "6-12-2018-06:25:25");
// ...
temp.Add("KeyN", "1");
allData .Add(temp);
temp = new Dictionary<string,string>();
temp.Add("Key1", "test3");
temp.Add("Key2", "12-12-2021-11:59:59");
// ...
temp.Add("KeyN", "1");
allData.Add(temp);
所以此時的列表將有 3 個字典對象。 我想根據 Key2 按升序或降序對所有這些進行排序。 任何幫助,將不勝感激。
temp.Orderby(dict => DateTime.ParseExact(dict["Key2"], some format));
您可以使用TryParseExact
檢查字典中的每個值是否與日期匹配。
下面就給大家梳理一下
Func<Dictionary<string, string>, DateTime> getDate = dict =>
dict.Values.FirstOrDefault(v =>
DateTime.TryParseExact(v, "d-M-yyyy hh:mm:ss", null, 0, out var dat) ? dat : default);
allData.Sort((a, b) => getDate(a).CompareTo(getDate(b)));
這會給你一個新的列表
var newList = allData.OrderBy(dict =>
dict.Values.FirstOrDefault(v =>
DateTime.TryParseExact(v, "d-M-yyyy hh:mm:ss", null, 0, out var dat) ? dat : default
));
IComparer<Dictionary<string, string>> asc = Comparer<Dictionary<string, string>>.Create((d1, d2) => DateTime.Parse(d1["Key2"]).CompareTo(DateTime.Parse(d2["Key2"])));
IComparer<Dictionary<string, string>> desc = Comparer<Dictionary<string, string>>.Create((d1, d2) => DateTime.Parse(d2["Key2"]).CompareTo(DateTime.Parse(d1["Key2"])));
allData.Sort(asc);
allData.Sort(desc);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.