我有以下列表:
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";
我想缩短长度,或者说从位置3和4开始销毁元素。我使用了以下代码但是当我mylist.Count
for(int i=0; i<mylist.Count; i++)
{
if(i>2)
{
mylist[i] = null;
}
}
我希望在mylist.Count
答案 0 :(得分:6)
执行此操作时:
mylist[i] = null;
您确实将i
元素设置为null,因此您不会更改列表的大小。基本上你会在那里null
:
// true
bool elementIsNull = mylist[i] == null;
使用RemoveRange
方法:
// remove 2 elements starting at element with index 3
mylist.RemoveRange(3, 2);
答案 1 :(得分:0)
取决于你如何定义“destroy”
如果你想从列表中删除元素并“销毁”单元格以减少列表列表,你可以使用RemoveAt
- 但它会缩短列表
如果你想“破坏”这个元素,那么GC会照顾它,只要没有人持有对这个元素的引用
答案 2 :(得分:0)
这取决于Destroy
的含义。
如果MyOwnList
实施IDisposable
,您可以使用:
int startIndex;
int numberOfItemsToRemove;
mylist.GetRange(startIndex, numberOfItemsToRemove).ForEach(m => m.Dispose());
mylist.RemoveRange(startIndex, numberOfItemsToRemove);
否则:
int startIndex;
int numberOfItemsToRemove;
mylist.RemoveRange(startIndex, numberOfItemsToRemove);
答案 3 :(得分:0)
您必须反向删除项目以避免indexoutofrange异常,并且请不要使用在循环条件下将要更改的列表属性
试试这个:
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);