tags:

views:

63

answers:

3

Is there a way to point to the last item added to a generic list in c# ? Like the back() for a vector in c++

+2  A: 
List<int> myList = new List<int>();

for( int i = 0; i < 5; i++ )
{
   myList.Add (i);
}

Console.WriteLine (String.Format ("Last item: {0}", myList[myList.Count - 1]));
Frederik Gheysels
thanks for that mate much appreciated
dbomb101
+2  A: 

list.Last() ?

Jan Jongboom
Seems that I have to 'think LINQ' more ... :)
Frederik Gheysels
Last() probably wraps around list[list.Count-1] so it doesn't even bother after all :-)
Jan Jongboom
Very possible, but it is more elegant and readable.
Frederik Gheysels
+2  A: 

If you're using the 3.5 framework


    using System.Linq;
    using System.Collections.Generic;
    public static class Program {
       public static void Main() {
           Console.WriteLine(new List<int> { 1, 2, 3 }.Last()); // outputs - 3
       }
    }
Dave