简体   繁体   English

如何删除添加到列表中的最后一个元素?

[英]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.我在 c# 中有一个列表,我在其中添加列表字段。现在在添加时我必须检查条件,如果条件满足,那么我需要从列表中删除最后一行。 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#.所以我的问题是如何从 C# 中的列表中删除最后一行。 Please help me.请帮我。

我认为最有效的方法是使用RemoveAt

rows.RemoveAt(rows.Count - 1)

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. TBH,我会更进一步,针对user.""测试"Something" user."" ,除非满足条件,否则甚至不实例化Row ,但作为user.""查看user.""不会编译,我将其保留为读者练习。

rows.RemoveAt(rows.Count - 1);

您可以使用List<T>.RemoveAt方法:

rows.RemoveAt(rows.Count -1);

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:甚至可以代替 void 返回值,例如:

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 ...请注意,第二个方法的返回类型不是 void ,它是字符串b/c 我们希望该函数返回一个字符串...

I would rather use Last() from LINQ to do it.我宁愿使用 LINQ 中的Last()来做到这一点。

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

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM