C# ArrayList - AddRange() 方法
C# ArrayList AddRange() 方法用于将 Icollection 的元素添加到 ArrayList 的末尾。
Icollection 表示一个集合对象,它提供一些基本操作,例如添加、移除、检查元素数量以及以数组形式访问集合。集合本身不能为空,但可以包含空元素。
语法
以下是 C# ArrayList AddRange() 方法的语法 -
public virtual void AddRange (System.Collections.ICollection c);
参数
此方法接受一个 ICollection 参数,用于将其元素添加到 ArrayList 的末尾 -
返回值
此方法不返回值。
示例 1:在范围内添加元素
这是 ArrayList 集合的基本示例,用于演示 AddRange() 方法的用法 -
using System; using System.Collections; class Program { static void Main() { ArrayList arrayList = new ArrayList(); // 创建另一个集合 string[] itemsToAdd = { "Item1", "Item2", "Item3" }; arrayList.AddRange(itemsToAdd); // 显示ArrayList的元素 foreach (var item in arrayList) { Console.WriteLine(item); } } }
输出
以下是输出 -
Item1 Item2 Item3
示例 2:添加整数数组
让我们看另一个使用 ArrayList 的 AddRange() 方法的示例,该示例用于在 ArrayList 中添加整数数组 -
using System; using System.Collections; class Program { static void Main() { ArrayList arrayList = new ArrayList(); // 创建另一个集合 int[] itemsToAdd = { 1, 2, 3, 4, 5 }; arrayList.AddRange(itemsToAdd); // 显示ArrayList的元素 Console.WriteLine("Items of ArrayList -"); foreach (var item in arrayList) { Console.Write(item + " "); } } }
输出
以下是输出 -
Items of ArrayList - 1 2 3 4 5
示例 3:添加另一个 ArrayList 的元素
在此示例中,我们使用 AddRange 方法将元素添加到一个 ArrayList 的 ArrayList 中 -
using System; using System.Collections; class Program { static void Main() { // 创建第一个 ArrayList ArrayList arrayList1 = new ArrayList(){10, 20}; // 创建另一个 ArrayList ArrayList arrayList2 = new ArrayList(); arrayList2.Add(30); arrayList2.Add(40); // 将 arrayList2 中的所有元素添加到 arrayList1 中 arrayList1.AddRange(arrayList2); Console.WriteLine("Elements of the ArrayList1 - "); foreach (var item in arrayList1) { Console.Write(item + " "); } } }
输出
以下是输出 -
Elements of the ArrayList1 - 10 20 30 40
示例 4:从列表添加元素
在此示例中,我们使用 AddRange() 方法将列表元素添加到 ArrayList 中 -
using System; using System.Collections; using System.Collections.Generic; class Program { static void Main() { ArrayList arrayList = new ArrayList(){"A", "b"}; // 创建字符串列表(ICollection) List<string> list = new List<string> { "C", "D", "E" }; // 将 List 中的所有元素添加到 ArrayList arrayList.AddRange(list); Console.WriteLine("Elements of the ArrayList"); foreach (var item in arrayList) { Console.Write(item + " "); } } }
输出
以下是输出 -
Elements of the ArrayList A b C D E