Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find List<T> second to last element

Tags:

c#-4.0

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

like image 741
GPGVM Avatar asked Dec 11 '22 09:12

GPGVM


1 Answers

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];
}
like image 65
psubsee2003 Avatar answered Feb 10 '23 17:02

psubsee2003