Remove n number of rows from a list

3110 views c#

How do I remove the last two rows from a List.

At present, I am removing the 2 rows manually as shown below. However, there might be an instance where I have to define the number of rows to be removed as n. So, it will remove n number of rows from the bottom of the list. How can I make this change?

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

answered question

There's a bug in your code. Once you've removed the last item with rows.RemoveAt(rows.Count - 1);, the code to remove the next last item is rows.RemoveAt(rows.Count - 1);.

3 Answers


You could use LINQ:

rows = rows.Take(rows.Count - n).ToList();

posted this

You could use RemoveRange:

rows.RemoveRange(rows.Count - n, n);

posted this

As Spender said, there is a potential issue in your code. I call this a "Index Race Condition". After you remove the last element, something else becomes the new last Element. It is something you have to look out for with Indexed Collections. Keyd collections do not suffer from it.

In addition to what others said regarding using "RemoveRange" (if availible) or LINQ, there is also a chance you got the wrong collection type.

The Queue[T] and the Stack[T] are specialized collections for first-in, first-out and first-in, last-out cases respectively.

posted this

Have an answer?


Please login first before posting an answer.