Find the list <T> from the second to the last item
I would like to find the second to last item in the list. One article came up with the search terms that I used, and they suggested getting the index of the last item, and then backing up one step. Is this really a way to do this ....? Seems curious kludgy / hardcoded. Maybe I'm too paranoid?
int _lstItemIdx = List<MyObj>.IndexOf(List<MyObj>.Last()); int _sndLstItmIdx = (_lstItemIdx - 1); thanks
+4
1 answer
What happened with:
var result = myList[myList.Count-2]; Of course, you need appropriate exception handling if your list does not contain 2 items.
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]; } +10