How to sort a dictionary by DateTime value

I have this dictionary

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

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

How can this be done in code?

Thank!

+3
source share
2 answers

You have the wrong data structure to achieve what you want. The purpose of the dictionary is to provide quick access to the key. There is a SortedDictionary that sorts its own keys, but there is no dictionary that sorts its values, because that makes no sense.

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

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

, .

+5

Dictionary, , LINQ:

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

, - Dictionary, , . ; .

+6