Removes the last element from the list and returns it. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Removes the last element from the list and returns it.

Demo Code


using System.Collections.Generic;
using System;/*from   w w  w .j a v  a2  s .c o m*/

public class Main{
    /// <summary>
      ///     Removes the last element from the list and returns it.
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="list"></param>
      /// <returns></returns>
      public static T PopLast<T>(this List<T> list) {
         var last = list.LastItem();
         list.RemoveAt(list.Count - 1);
         return last;
      }
    /// <summary>
      ///     Returns the last element of the list.
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="list"></param>
      /// <returns></returns>
      public static T LastItem<T>(this List<T> list) {
         return list[list.Count - 1];
      }
}

Related Tutorials