繁体   English   中英

排序列表<dictionary<string,string> > 基于特定的键值</dictionary<string,string>

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM