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

我在c#中有一个List,我在其中添加列表字段。现在添加i时必须检查条件,如果条件满足,那么我需要删除列表中添加的最后一行。 这是我的示例代码..

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

所以我的问题是如何从c#中的列表中删除最后一行。 请帮我。

现在看到这个问题在搜索引擎中表现得很好,这个问题的直接答案是:

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

但是……在这个问题的特定情况下,首先添加行更有意义:

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

TBH,我更进一步测试"Something"user."" ,甚至没有实例化Row除非条件满足,但看作user.""将无法编译,我会留下为读者练习。

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

 rows.RemoveAt(rows.Count - 1) 
 rows.RemoveAt(rows.Count - 1); 

您可以使用List.RemoveAt方法:

 rows.RemoveAt(rows.Count -1); 

如果你需要更频繁地做,你甚至可以创建自己的方法来弹出最后一个元素; 像这样的东西:

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

甚至可以代替void,你可以返回如下值:

 public string pop (List 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; } 

只是注意到第二个方法的返回类型不是void,它是字符串 b / c我们希望该函数返回一个字符串…