Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Second To Last Element For SortedDictionary

I have a sorted dictionary that looks like such:

SortedDictionary<DateTime, string> mySortedDictionary = GetDataSource();

To get the last element, I noticed that I am able to do this:

DateTime last = Convert.ToDateTime(mySortedDictionary.Keys.Last());

Is there any way to get the second-to-last item? The way that I am currently thinking of involves getting the last item and then calculating what the second to last item would be. My DateTime keys all have a set pattern, however, it is not guaranteed that I know them exactly.

like image 435
Rhs Avatar asked Nov 30 '25 03:11

Rhs


2 Answers

dictionary.Keys.Reverse().Skip(1).FirstOrDefault()

This will take O(n) time, but I as far as I can tell there seems to be no fast solution.

like image 178
Daniel Brückner Avatar answered Dec 02 '25 17:12

Daniel Brückner


Using linq you can skip all items until the second to last and take the first one (but first check if the dictionary has at least 2 elements):

var secondToLast = mySortedDictionary.Skip(mySortedDictionary.Count - 2).First();
like image 40
david.s Avatar answered Dec 02 '25 17:12

david.s