Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort dictionary by DateTime value

I have this Dictionary

Dictionary<Guid, DateTime> myDic = new Dictionary<Guid, DateTime>();

What is the best approach to sort it DESC by DateTime? Is it LINQ?

How it could be done in code?

Thank you!

like image 970
Friend Avatar asked Oct 21 '25 23:10

Friend


1 Answers

You cannot sort a Dictionary without relying on details of current implementation, but you can process its entries in any specific order using LINQ's sorting functionality:

foreach (KeyValuePair<Guid,DateTime> pair in myDict.OrderByDescending(p => p.Value)) {
    // do some processing
}

Purely as a curiosity, you can pass ordered key-value pairs to Dictionary's constructor, and the resulting dictionary will enumerate in the order the items were provided in the enumeration to the constructor. However, relying on this functionality is very dangerous; you should not do it in your code.

like image 187
Sergey Kalinichenko Avatar answered Oct 24 '25 13:10

Sergey Kalinichenko