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的返回值,这句就是利用了这点。
二、程序代码
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();
本文介绍了一种使用C# List类的Remove方法来删除列表中所有指定元素的有效方法。通过一个简单的循环结构,可以轻松实现类似RemoveAll的功能。
循环的Remove方法&spm=1001.2101.3001.5002&articleId=50642686&d=1&t=3&u=17f7c0670ad44e3a87a519183729403c)
2321

被折叠的 条评论
为什么被折叠?



