C#⼩技巧(⼀)循环的Remove⽅法
C#⼩技巧——⽤循环的Remove⽅法实现RemoveAll的部分功能
⼀、程序功能
我们知道,List类⾃带有⼀个Remove⽅法,该⽅法可以删除第⼀个在List出现的指定对象。⽽在实际编程中,我们常常会遇到要把该指定对象的所有项都删除的情况,应该怎么做才能⽐较简洁的实现该功能呢?
⽐如有⼀个List列表如下:
List<string> strList = new List<string> { "car", "bike", "truck", "car", "plane", "car" };
其中“car”是重复出现的对象,我们要把他们都删除,⽤⼀句程序就可以。如下:
while (strList.Remove("car")) ;
因为Remove⽅法会有bool的返回值,这句就是利⽤了这点。
⼆、程序代码
writeline方法的作用List<string> strList = new List<string> { "car", "bike", "truck", "car", "plane", "car" };
string str_delete = "car";
while (strList.Remove(str_delete)) ;
Console.WriteLine("删除所有指定项之后");
foreach(string s in strList)
{
Console.WriteLine(s);
}
Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。