Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last element added into the List?

Tags:

c#

list

arraylist

I have a List in c# in which i am adding list fields.Now while adding i have to check condition,if the condition satisfies then i need to remove the last row added from the list. Here is my sample code..

    List<> rows = new List<>();     foreach (User user in users)     {         try         {             Row row = new Row();             row.cell = new string[11];             row.cell[1] = user."";             row.cell[0] = user."";             row.cell[2] = user."";                       rows.Add(row);              if (row.cell[0].Equals("Something"))             {                  //here i have to write code to remove last row from the list                 //row means all the last three fields              }          } 

So my question is how to remove last row from list in c#. Please help me.

like image 866
Pranav Avatar asked Apr 23 '14 13:04

Pranav


People also ask

How do I remove the last element from a list?

The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.

How do you remove the last element of a list in Java?

We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.


Video Answer


1 Answers

I think the most efficient way to do this is this is using RemoveAt:

rows.RemoveAt(rows.Count - 1) 
like image 162
Patrick Hofman Avatar answered Oct 03 '22 08:10

Patrick Hofman