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


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

      



It will take time O(n)

, but I don't seem to have a quick fix as far as I can tell.

+1


source


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



var secondToLast = mySortedDictionary.Skip(mySortedDictionary.Count - 2).First();

      

+3


source


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


Can you save the keys in reverse order? In this case, you can simply use mySortedDictionary.Skip(1).FirstOrDefault()

.

You can reverse the sort order of keys by specifying a (simple) custom one IComparer

in the constructor.

0


source







All Articles