Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort Dictionary based on keys where key contains Month Year expression of DateTime as String

I am trying to sort below Dictionary

Dictionary<string, int> map = new Dictionary<string, int>();
map["Sep 20"] = 10;
map["Oct 20"] = 11;
map["Nov 20"] = 23;
map["Jan 21"] = 15;
map["Feb 20"] = 50;
map["Mar 20"] = 23;

I have tried to used SortedDictionary to sort Dictionary as follows

SortedDictionary<string, int> sortMap = new SortedDictionary<string, int>(map);

foreach (var entry in sortMap)
{
  Console.WriteLine (entry.Key+"\t"+entry.Value);
}

This is I am expecting as output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Feb 20  50
Mar 20  23
Sep 20  10
Oct 20  11
Nov 20  23
Jan 21  15

But, I am getting actual output as follows

Feb 20  50
Jan 21  15
Mar 20  23
Nov 20  23
Oct 20  11
Sep 20  10

>Solution :

You can use DateTime.ParseExact and LINQ:

 map = map
    .Select(kv => (KV: kv, DT: DateTime.ParseExact(kv.Key, "MMM yy", CultureInfo.InvariantCulture)))
    .OrderBy(x => x.DT)
    .ToDictionary(x => x.KV.Key, x => x.KV.Value);

However, if you want to use this Dictionary<TKey, TValue> you should not rely on the order if you plan to modify it. If you add or remove items, the enumerator might return the key-value-pairs in a different order. So if you have to do this often, you better use a SortedDictionary<TKey, TValue>> or a simple List<T>(T could be a class or a KeyValuePair<TKey, TValue>).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading