Reputation: 35
I need a little help. I have 2 lists in my project: 1 has 5,000 items, listA
, and the other has 10,000 items, listB
. I am reading the list using a for loop
:
for(int j = 5000 - 1; j > 0; j--)
I need to delete the last item in listA
,and in listB
, I need to delete the last 2 items. This process is necessary because I need to optimize memory in my software.
i really appreciate any help Thanks
I tried to do this, but it doesn't work:
listA.RemoveAt(j);
listB.RemoveAt(9999 - i + 1);
listB.RemoveAt(9999 - i );
Upvotes: 0
Views: 98
Reputation: 149000
Since j
seems to always be equal to the index of the last item in listA
, 2 * j + 1
is always equal to the index of the last item in listB
. So you could just use RemoveAt
/ RemoveRange
:
listA.RemoveAt(j);
listB.RemoveRange(2 * j, 2);
Also, if memory management is a big concern you might want to consider shrinking your list after a while by setting the Capacity
(note that this can have performance impacts so you should avoid doing this too eagerly).
listA.Capacity = j;
listB.Capacity = 2 * j;
Upvotes: 0
Reputation: 2923
To delete the last item do
listA.RemoveAt(listA.Count - 1)
For the last two items simply execute it twice. You should check though wether the count is already 0, otherwise you'll get an exception.
Upvotes: 3