Pranav
Pranav

Reputation: 881

How to remove the last element added into the List?

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.

Upvotes: 84

Views: 229898

Answers (6)

spender
spender

Reputation: 120450

The direct answer to this question is:

if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
    rows.RemoveAt(rows.Count - 1);
}

However... in the specific case of this question, it makes more sense not to add the row in the first place:

Row row = new Row();
//...      

if (!row.cell[0].Equals("Something"))
{
    rows.Add(row);
}

TBH, I'd go a step further by testing "Something" against user."", and not even instantiating a Row unless the condition is satisfied, but seeing as user."" won't compile, I'll leave that as an exercise for the reader.

Upvotes: 94

Liakat Hossain
Liakat Hossain

Reputation: 1384

I would rather use Last() from LINQ to do it.

rows = rows.Remove(rows.Last());

or

rows = rows.Remove(rows.LastOrDefault());

Upvotes: -3

amdev
amdev

Reputation: 7442

if you need to do it more often , you can even create your own method for pop the last element; something like this:

public void pop(List<string> myList) {
    myList.RemoveAt(myList.Count - 1);
}

or even instead of void you can return the value like:

public string pop (List<string> myList) {
    // first assign the  last value to a seperate string 
    string extractedString = myList(myList.Count - 1);
    // then remove it from list
    myList.RemoveAt(myList.Count - 1);
    // then return the value 
    return extractedString;
}

just notice that the second method's return type is not void , it is string b/c we want that function to return us a string ...

Upvotes: 3

Pradip Daunde
Pradip Daunde

Reputation: 421

rows.RemoveAt(rows.Count - 1);

Upvotes: 14

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can use List<T>.RemoveAt method:

rows.RemoveAt(rows.Count -1);

Upvotes: 9

Patrick Hofman
Patrick Hofman

Reputation: 156968

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

rows.RemoveAt(rows.Count - 1)

Upvotes: 129

Related Questions