C# | Copy the elements of a string array to the end of the StringCollection
Last Updated :
01 Feb, 2019
StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.
StringCollection.AddRange(String[]) method is used to copy the elements of a string array to the end of the StringCollection.
Syntax:
public void AddRange (string[] value);
Here, string[] value is an array of strings which will be added to the end of the StringCollection. The array itself can not be null but it can contain elements that are null.
Exception: This method will give ArgumentNullException if value is null.
Note:
- StringCollection accepts null as a valid value and allows duplicate elements.
- If the StringCollection can accommodate the new elements without increasing the capacity, this method is an O(n) operation, where n is the number of elements to be added. If the capacity needs to be increased to accommodate the new elements, this method becomes an O(n + m) operation, where n is the number of elements to be added and m is Count.
Below programs illustrate the use of StringCollection.AddRange(String[]) Method:
Example 1:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr = new String[] { "A" , "B" , "C" , "D" , "E" };
myCol.AddRange(myArr);
foreach (Object obj in myCol)
{
Console.WriteLine( "{0}" , obj);
}
}
}
|
Example 2:
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
public static void Main()
{
StringCollection myCol = new StringCollection();
String[] myArr = new String[] { "2" , "3" , "4" , "5" , "6" };
myCol.AddRange(myArr);
foreach (Object obj in myCol)
{
Console.WriteLine( "{0}" , obj);
}
}
}
|
Reference:
Share your thoughts in the comments
Please Login to comment...