C#将元素添加到ArrayList的末尾

ArrayList.AddRange(ICollection)方法用于将ICollection的元素添加到数组列表.
语法如下:

public virtual void AddRange (System.Collections.ICollection c);

这里, C是ICollection, 其元素应添加到ArrayList的末尾。集合本身不能是null, 但可以包含以下元素null.
例外情况:
  • ArgumentException:IfC一片空白
  • NotSupportedException:如果ArrayList为只读或ArrayList具有固定大小。
下面的程序说明了上述方法的用法:
示例1:
//C# code to add the elements of an //ICollection to the end of the ArrayList using System; using System.Collections; class GFG {//Driver code public static void Main() {//Creating an ArrayList ArrayList myList = new ArrayList(); //Adding elements to ArrayList myList.Add( "A" ); myList.Add( "B" ); myList.Add( "C" ); myList.Add( "D" ); myList.Add( "E" ); myList.Add( "F" ); Console.WriteLine( "Before AddRange Method" ); Console.WriteLine(); //displaying the item of myList foreach (String str in myList) { Console.WriteLine(str); }Console.WriteLine( "\nAfter AddRange Method\n" ); //Here we are using AddRange method //Which adds the elements of myList //Collection in myList again i.e. //we have copied the whole myList //in it myList.AddRange(myList); //displaying the item of List foreach (String str in myList) { Console.WriteLine(str); } } }

【C#将元素添加到ArrayList的末尾】输出如下:
Before AddRange MethodABCDEFAfter AddRange MethodABCDEFABCDEF

示例2:
//C# code to add the elements of an //ICollection to the end of the ArrayList using System; using System.Collections; class GFG {//Driver code public static void Main() {//Creating an ArrayList ArrayList myList = new ArrayList(); //adding elements in myList myList.Add( "Geeks" ); myList.Add( "GFG" ); myList.Add( "C#" ); myList.Add( "Tutorials" ); Console.WriteLine( "Before AddRange Method" ); Console.WriteLine(); //displaying the item of myList foreach (String str in myList) { Console.WriteLine(str); }Console.WriteLine( "\nAfter AddRange Method\n" ); //taking array of String string [] str_add = { "Collections" , "Generic" , "List" }; //here we are adding the elements //of the str_add to the end of //the myList myList.AddRange(str_add); //displaying the item of List foreach (String str in myList) { Console.WriteLine(str); } } }

输出如下:
Before AddRange MethodGeeksGFGC#TutorialsAfter AddRange MethodGeeksGFGC#TutorialsCollectionsGenericList

注意:
  • ArrayList接受null作为有效值, 并允许重复的元素。
  • ICollection中元素的顺序保留在ArrayList中。
参考:
  • https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.addrange?view=netframework-4.7.2

    推荐阅读