How to remove the last element added into the List?

前端 未结 6 1176
耶瑟儿~
耶瑟儿~ 2020-12-18 17:40

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

相关标签:
6条回答
  • 2020-12-18 18:06

    You can use List<T>.RemoveAt method:

    rows.RemoveAt(rows.Count -1);
    
    0 讨论(0)
  • 2020-12-18 18:15

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

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

    or

    rows = rows.Remove(rows.LastOrDefault());
    
    0 讨论(0)
  • 2020-12-18 18:17

    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 ...

    0 讨论(0)
  • 2020-12-18 18:25

    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.

    0 讨论(0)
  • 2020-12-18 18:25
    rows.RemoveAt(rows.Count - 1);
    
    0 讨论(0)
  • 2020-12-18 18:26

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

    rows.RemoveAt(rows.Count - 1)
    
    0 讨论(0)
提交回复
热议问题