志在指尖
用双手敲打未来

C#中List汇合运用Remove办法移除指定的对象

C#的List汇合操作中,有时分需求将特定的对象或者元素移除出List汇合序列中,此时可运用到List汇合的Remove办法,Remove办法的办法签名为boolRemove(Titem),item代表详细的List汇合中的对象,T是C#中泛型的表达方式。
(1)例如有个List汇合list1中含有元素1至10,需求移除元素5可运用下列语句:
List<int>list1=newList<int>(){1,2,3,4,5,6,7,8,9,10};
list1.Remove(5);C#
(2)假如是援用类型,需求依据详细的对象来移除,并且对象的援用地址跟List汇合中的元素的援用地址分歧,详细如下:
首先定义一个自定义类TestModel类,详细构造如下
复制代码
publicclassTestModel
{
publicintIndex{set;get;}
publicstringName{set;get;}
}
复制代码
然后定义个List的List汇合,然后往汇合中添加两个元素,添加终了后再移除Index=1的元素对象。
复制代码
ListtestList=newList<ConsoleApplication1.TestModel>();
testList.Add(newConsoleApplication1.TestModel()
{
Index=1,
Name=”Index1″
});
testList.Add(newConsoleApplication1.TestModel()
{
Index=2,
Name=”Index2″
});
varwhereRemove=testList.FirstOrDefault(t=>t.Index==1);
testList.Remove(whereRemove);
复制代码
上述语句执行胜利后,testList只要一个元素,只要Index=2的那个元素对象。假如上述Remove办法采取下列写法,将不会停止移除,由于固然对象中一切属性值都一样,但元素的援用地址不同,不在List汇合内。
varwhereRemove=newTestModel(){Index=1,Name=”Index1″};
testList.Remove(whereRemove);

未经允许不得转载:IT技术网站 » C#中List汇合运用Remove办法移除指定的对象
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载