删除与 C# 中谓词定义的条件相匹配的列表中的所有元素
要删除与谓词定义的条件相匹配的列表中的所有元素,代码如下所示 −
示例
using System; using System.Collections.Generic; public class Demo { private static bool demo(int i){ return (i == 500); } public static void Main(String[] args){ List<int> list = new List<int>(); list.Add(100); list.Add(500); list.Add(300); list.Add(400); list.Add(500); list.Add(600); list.Add(500); Console.WriteLine("List elements..."); foreach (int i in list){ Console.WriteLine(i); } Console.WriteLine(" "); list.RemoveAll(demo); Console.WriteLine("List after removing elements 500..."); foreach (int i in list){ Console.WriteLine(i); } } }
输出
这将产生以下输出 −
List elements... 100 500 300 400 500 600 500 List after removing elements 500... 100 300 400 600
示例
我们来看另一个示例 −
using System; using System.Collections.Generic; public class Demo { private static bool demo(int i){ return ((i % 10) == 0); } public static void Main(String[] args){ List<int> list = new List<int>(); list.Add(100); list.Add(295); list.Add(355); list.Add(450); list.Add(550); Console.WriteLine("List elements..."); foreach (int i in list){ Console.WriteLine(i); } Console.WriteLine(" "); list.RemoveAll(demo); Console.WriteLine("List after removing elements..."); foreach (int i in list){ Console.WriteLine(i); } } }
输出
这将产生以下输出 −
List elements... 100 295 355 450 550 List after removing elements... 295 355
广告