[英]Sorting a List<Dictionary<string,string>> based on a specific keys value
I have a collections of Dictionary objects.我有一个 collections 的 Dictionary 对象。
Example:例子:
List<Dictionary<string,string>> allData = new List<Dictionary<string,string>>();
I have about 30 entries in each Dictionary object, one of them is a DateTime saved as a string.我在每个 Dictionary object 中大约有 30 个条目,其中一个是保存为字符串的 DateTime。 I want to sort the List of Dictionary objects based on the specific key that has the DateTime field saved as a string in descending/ascending order.我想根据特定键对字典对象列表进行排序,该特定键将 DateTime 字段按降序/升序保存为字符串。
Example Data:示例数据:
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);
So the List at this point would have 3 dictionary objects.所以此时的列表将有 3 个字典对象。 I want to sorts all of them based on Key2 in ascending or descending order.我想根据 Key2 按升序或降序对所有这些进行排序。 Any help would be appreciated.任何帮助,将不胜感激。
temp.Orderby(dict => DateTime.ParseExact(dict["Key2"], some format));
You can use TryParseExact
to check each value in the dictionary for the one which matches a date.您可以使用TryParseExact
检查字典中的每个值是否与日期匹配。
The following will give you a sort in place下面就给大家梳理一下
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)));
This will give you a new list这会给你一个新的列表
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.