简体   繁体   中英

Sorting a List<Dictionary<string,string>> based on a specific keys value

I have a collections of Dictionary objects.

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. 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.

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. I want to sorts all of them based on Key2 in ascending or descending order. 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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