如何删除添加到列表中的最后一个元素?
我在 c# 中有一个列表,我在其中添加列表字段.现在添加时我必须检查条件,如果条件满足,则我需要从列表中删除添加的最后一行.这是我的示例代码..
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
}
}
所以我的问题是如何从 C# 中的列表中删除最后一行.请帮帮我.
So my question is how to remove last row from list in c#. Please help me.
这个问题的直接答案是:
The direct answer to this question is:
if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
rows.RemoveAt(rows.Count - 1);
}
注意: 从 c#8.0 开始,您可以使用 rows.RemoveAt(^1)
而不是 rows.RemoveAt(rows.Count - 1)
.
Note: Since c#8.0 you can use rows.RemoveAt(^1)
instead of 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,我会更进一步,针对 user.""
测试 "Something"
,甚至不实例化 Row
除非满足条件,但作为 user.""
将无法编译,我将其留给读者作为练习.
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.