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