How to find the second last item from a list?

I have a List<string> like:

  List<String> lsRelation = new List<String>{"99","86","111","105"}. 

Now I want to find the number 111, which is the second to the last line.

So I tried:

 String strSecondLast=lsrelation.Last() - 2; 

which does not work. So, how can I find the second for the last element of the list using Last() .

+11
source share
5 answers

Using:

 if (lsRelation.Count >= 2) secLast = lsRelation[lsRelation.Count - 2]; 
+11
source

If you know that IList<T> with index:

 string secondLast = null; if (lsRelation.Count >= 2) secondLast = lsRelation[lsRelation.Count - 2]; 

You can create an extension, for example:

 public static T SecondLast<T>(this IEnumerable<T> items) { if (items == null) throw new ArgumentNullException("items"); IList<T> list = items as IList<T>; if (list != null) { int count = list.Count; if (count > 1) { return list[count - 2]; } else throw new ArgumentException("Sequence must contain at least two elements.", "items"); } else { try { return items.Reverse().Skip(1).First(); } catch (InvalidOperationException) { throw new ArgumentException("Sequence must contain at least two elements.", "items"); } } } 

Then you can use it as follows:

 string secondLast = lsRelation.SecondLast(); 
+8
source

There are many options for this. Just to mention what I haven't seen here yet:

 List<string> lsRelation = new List<String>{"99","86","111","105"}; String strSecondLast = lsRelation.Skip(lsRelation.Count() - 2).First(); 
+6
source

You can use ElementAt(list.Count - 2) :

 List<String> lsRelation = new List<String> { "99", "86", "111", "105" }; Console.WriteLine(lsRelation.ElementAt(lsRelation.Count - 2)); // 111 
+5
source

You cannot do this using Last() . Try it. You take the length of the list and subtract 2:

 if (lsRelation.Count >= 2) { var item = lsRelation[lsRelation.Count - 2]; } 

Edit:

Based on the comment, here is an example of using the Last() method, which would be ridiculous to use:

 if (lsRelation.Count >= 2) { var item = lsRelation.Last(x => x == lsRelation[lsRelation.Count - 2]); } 
+3
source

All Articles