gpt4 book ai didi

c# - 如何在 C# 中销毁列表数组的元素(或缩短长度)

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:18 44 4
gpt4 key购买 nike

我有以下列表:

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

时它仍然打印“5”
for(int i=0; i<mylist.Count; i++)
{
if(i>2)
{
mylist[i] = null;
}
}

我希望它在我执行 mylist.Count

时打印“3”

最佳答案

当你这样做时:

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);

关于c# - 如何在 C# 中销毁列表数组的元素(或缩短长度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216346/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com