How to sort dictionary by DateTime value

10,131

Solution 1

You have the wrong data structure to achieve what you want. The purpose of a dictionary is to provide fast access by key. A SortedDictionary exists that sorts its own keys, but there is no dictionary that sorts its values because that doesn't make sense.

Assuming all you need is the DateTimes contained in myDic sorted descending, you could do:

var dateTimesDescending = myDic.Values.OrderByDescending(d => d);

That will allow you to enumerate the values in descending order, but will not sort the dictionary.

Solution 2

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.

Share:
10,131
NoWar
Author by

NoWar

[email protected]

Updated on June 04, 2022

Comments

  • NoWar
    NoWar almost 2 years

    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!