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
You can use List<T>.RemoveAt
method:
rows.RemoveAt(rows.Count -1);
I would rather use Last()
from LINQ to do it.
rows = rows.Remove(rows.Last());
or
rows = rows.Remove(rows.LastOrDefault());
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 ...
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.
rows.RemoveAt(rows.Count - 1);
I think the most efficient way to do this is this is using RemoveAt:
rows.RemoveAt(rows.Count - 1)