Get the second for the last element for a SortedDictionary
I have a sorted dictionary that looks like this:
SortedDictionary<DateTime, string> mySortedDictionary = GetDataSource();
To get the last element, I noticed that I can do this:
DateTime last = Convert.ToDateTime(mySortedDictionary.Keys.Last());
Is there a way to get the second to last item? What I'm thinking about now involves getting the last element and then calculating what will be the last for the last element. My DateTime keys have a set of patterns, but I am not guaranteed to know them exactly.
+3
source to share
4 answers
You can use this method to get from the second to the last item. Note that to get it, you need to iterate over the entire key sequence to be ineffective. Also note that I mostly ignored the 0 or 1 sequence cases; you can check it and throw it or do something else if you don't want to get the default.
public static T SecondToLast<T>(this IEnumerable<T> source)
{
T previous = default(T);
T current = default(T);
foreach (var item in source)
{
previous = current;
current = item;
}
return previous;
}
To use it:
DateTime secondToLast = mySortedDictionary.Keys.SecondToLast();
0
source to share