C# | Adding elements to the end of the ArrayList
AddRange(ICollection) Method is used to add the elements of an ICollection to the end of the ArrayList. Or in other words, this method is used to add the multiple elements from other collection into an ArrayList. Here elements are defined as the primitive or non-primitive type.
Syntax:
public virtual void AddRange (ICollection col);
Here, col is an ICollection whose elements should be added to the end of the ArrayList. The collection itself cannot be null, but it can contain null elements.
Exception:
- If the value of col is null then this method will give ArgumentNullException.
- This method will gives NotSupportedException if the ArrayList is read-only, or the ArrayList has a fixed size
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
class GFG {
public static void Main()
{
ArrayList mylist = new ArrayList();
mylist.Add( "C# " );
mylist.Add( "DSA " );
mylist.Add( "Java " );
mylist.Add( "CPP" );
Queue mydata = new Queue();
mydata.Enqueue( "C " );
mydata.Enqueue( "Python " );
mydata.Enqueue( "HTML " );
mydata.Enqueue( "CSS " );
mydata.Enqueue( "JavaScript " );
mydata.Enqueue( "Ruby" );
Console.Write( "The original ArrayList: " );
Data(mylist);
Console.Write( "The original Queue: " );
Data(mydata);
mylist.AddRange(mydata);
Console.Write( "The new ArrayList is: " );
Data(mylist);
}
public static void Data(IEnumerable mylis)
{
foreach ( string str in mylis)
Console.Write( "{0}" , str);
Console.WriteLine();
}
}
|
Output:
The original ArrayList: C# DSA Java CPP
The original Queue: C Python HTML CSS JavaScript Ruby
The new ArrayList is: C# DSA Java CPPC Python HTML CSS JavaScript Ruby
Example 2:
using System;
using System.Collections;
public class GFG {
public static void Main()
{
ArrayList mylist = new ArrayList();
mylist.Add(5);
mylist.Add(10);
mylist.Add(15);
mylist.Add(20);
mylist.Add(25);
ArrayList mydata = new ArrayList();
mydata.Add(30);
mydata.Add(35);
mydata.Add(40);
mydata.Add(45);
mydata.Add(50);
Console.WriteLine( "The ArrayList 1: " );
foreach ( int i in mylist)
{
Console.WriteLine(i);
}
Console.WriteLine( "The ArrayList 2: " );
foreach ( int j in mydata)
{
Console.WriteLine(j);
}
mylist.AddRange(mydata);
Console.WriteLine( "The new ArrayList is :" );
for ( int k = 0; k < mylist.Count; k++)
Console.WriteLine(mylist[k]);
}
}
|
Output:
The ArrayList 1:
5
10
15
20
25
The ArrayList 2:
30
35
40
45
50
The new ArrayList is :
5
10
15
20
25
30
35
40
45
50
Reference:
Last Updated :
01 Feb, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...