Find List<T> second to last element

c#-4.0

Solution

What's wrong with:

var result = myList[myList.Count-2];

Of course, you need appropriate exception handling in case your list doesn't have 2 elements.

And you can turn it into an extension method:

public static T SecondToLast<T>(this IList<T> source)
{
    if (source.Count < 2)
        throw new ArgumentException("The list does not have at least 2 elements");

    return source[source.Count - 2];
}

Problem

I would like to find the second to the last item in a list. One article came up with the search terms I used and they suggested getting the index of the last element then backing up one step. Is this really the way to do it....? Seems kinda kludgy / hard coded. Perhaps I'm being too paranoid?? ``` int _lstItemIdx = List<MyObj>.IndexOf(List<MyObj>.Last()); int _sndLstItmIdx = (_lstItemIdx - 1); ``` Thank You

Original source