要从ArrayList中删除特定对象的首次出现,代码如下-
using System; using System.Collections; public class Demo { public static void Main(String[] args) { ArrayList list1 = new ArrayList(); list1.Add("A"); list1.Add("B"); list1.Add("C"); list1.Add("D"); list1.Add("E"); list1.Add("F"); list1.Add("G"); list1.Add("H"); list1.Add("I"); Console.WriteLine("Elements in ArrayList1..."); foreach (string res in list1) { Console.WriteLine(res); } ArrayList list2 = new ArrayList(); list2.Add("A"); list2.Add("B"); list2.Add("C"); list2.Add("D"); list2.Add("E"); list2.Add("F"); list2.Add("G"); list2.Add("H"); list2.Add("I"); list2.Add("G"); list2.Add("I"); Console.WriteLine("Elements in ArrayList2..."); foreach (string res in list2) { Console.WriteLine(res); } Console.WriteLine("Count of elements in ArrayList2 = " + list2.Count); list2.Remove("G"); Console.WriteLine("Elements in ArrayList2... (UPDATED)"); foreach (string res in list2) { Console.WriteLine(res); } Console.WriteLine("Count of elements in ArrayList2 (Updated) = " + list2.Count); } }
输出结果
这将产生以下输出-
Elements in ArrayList1... A B C D E F G H I Elements in ArrayList2... A B C D E F G H I G I Count of elements in ArrayList2 = 11 Elements in ArrayList2... (UPDATED) A B C D E F H I G I Count of elements in ArrayList2 (Updated) = 10
让我们看另一个例子-
using System; using System.Collections; public class Demo { public static void Main(String[] args) { ArrayList list = new ArrayList(); list.Add("Laptop"); list.Add("Dektop"); list.Add("Wearables"); list.Add("Tablet"); list.Add("Notebook"); list.Add("Ultrabooks"); Console.WriteLine("Elements in ArrayList..."); foreach (string res in list) { Console.WriteLine(res); } Console.WriteLine("Count of elements in ArrayList = " + list.Count); list.Remove("Tablet"); Console.WriteLine("Elements in ArrayList... (UPDATED)"); foreach (string res in list) { Console.WriteLine(res); } Console.WriteLine("Count of elements in ArrayList (Updated) = " + list.Count); } }
输出结果
这将产生以下输出-
Elements in ArrayList... Laptop Dektop Wearables Tablet Notebook Ultrabooks Count of elements in ArrayList = 6 Elements in ArrayList... (UPDATED) Laptop Dektop Wearables Notebook Ultrabooks Count of elements in ArrayList (Updated) = 5