Reputation: 3441
I have the following list:
List<MyOwnList> mylist = new List<MyOwnList>();
mylist[0].Name = "Name0";
mylist[0].Class = "Class0";
mylist[1].Name = "Name1";
mylist[1].Class = "Class1";
mylist[2].Name = "Name2";
mylist[2].Class = "Class2";
mylist[3].Name = "Name3";
mylist[3].Class = "Class3";
mylist[4].Name = "Name4";
mylist[4].Class = "Class4";
I want to shorten the length or let's say destroy elements from position 3 and 4. I used the following code but it still prints "5" when I do mylist.Count
for(int i=0; i<mylist.Count; i++)
{
if(i>2)
{
mylist[i] = null;
}
}
I expect it to print "3" when I do mylist.Count
Upvotes: 2
Views: 2078
Reputation: 1
You have to delete the items in reverse to avoid the indexoutofrange exception and please don't use a property of a list which is going to change in the condition of a loop
try this:
List<MyOwnList> mylist = new List<MyOwnList>();
mylist.Add(new MyOwnList { Name = "Name0", Class = "Class0" });
mylist.Add(new MyOwnList { Name = "Name1", Class = "Class1" });
mylist.Add(new MyOwnList { Name = "Name2", Class = "Class2" });
mylist.Add(new MyOwnList { Name = "Name3", Class = "Class3" });
mylist.Add(new MyOwnList { Name = "Name4", Class = "Class4" });
mylist[0].Name = "Name0";
mylist[0].Class = "Class0";
mylist[1].Name = "Name1";
mylist[1].Class = "Class1";
mylist[2].Name = "Name2";
mylist[2].Class = "Class2";
mylist[3].Name = "Name3";
mylist[3].Class = "Class3";
mylist[4].Name = "Name4";
mylist[4].Class = "Class4";
int count = mylist.Count;
for (int i = count - 1; i >= 0; i--)
{
if (i > 2)
{
mylist.RemoveAt(i);
//mylist[i] = null;
}
}
Console.WriteLine(mylist.Count);
Upvotes: 0
Reputation: 27604
When you do this:
mylist[i] = null;
you're accually setting i
th element to null, so you won't change size of your list. Basicaly you will have null
there:
// true
bool elementIsNull = mylist[i] == null;
Use RemoveRange
method:
// remove 2 elements starting at element with index 3
mylist.RemoveRange(3, 2);
Upvotes: 7
Reputation: 10456
It really depends what you mean by Destroy
.
If MyOwnList
implements IDisposable
, You would use:
int startIndex;
int numberOfItemsToRemove;
mylist.GetRange(startIndex, numberOfItemsToRemove).ForEach(m => m.Dispose());
mylist.RemoveRange(startIndex, numberOfItemsToRemove);
Otherwise:
int startIndex;
int numberOfItemsToRemove;
mylist.RemoveRange(startIndex, numberOfItemsToRemove);
Upvotes: 0
Reputation: 5260
it's depend how you define "destroy"
if you want to remove the element from the list and "destroy" the cell to reduce the list list you can use the RemoveAt
- BUT it would shorten the list
if you want to "destroy" the element , GC will take care of that , as long no one is holding reference to this element
Upvotes: 0