Copy StringCollection at the specified index of array in C#


To copy StringCollection at the specified index of the array, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringCollection strCol = new StringCollection();
      String[] strArr = new String[] { "Tim", "Tom", "Sam", "Mark", "Katie", "Jacob"};
      Console.WriteLine("Elements...");
      for (int i = 0; i < strArr.Length; i++) {
         Console.WriteLine(strArr[i]);
      }
      strCol.AddRange(strArr);
      String[] arr = new String[strCol.Count];
      strCol.CopyTo(arr, 0);
      Console.WriteLine("Elements...after copying StringCollection to array");
      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}

Output

This will produce the following output −

Elements...
Tim
Tom
Sam
Mark
Katie
Jacob
Elements...after copying StringCollection to array
Tim
Tom
Sam
Mark
Katie
Jacob

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringCollection strCol = new StringCollection();
      String[] strArr = new String[] { "Tim", "Tom", "Sam", "Mark", "Katie", "Jacob", "David"};
      Console.WriteLine("Elements...");
      for (int i = 0; i < strArr.Length; i++) {
         Console.WriteLine(strArr[i]);
      }
      strCol.AddRange(strArr);
      String[] arr = new String[10];
      strCol.CopyTo(arr, 3);
      Console.WriteLine("Elements...after copying");
      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}

Output

This will produce the following output −

Elements...
Tim
Tom
Sam
Mark
Katie
Jacob
David
Elements...after copying

Tim
Tom
Sam
Mark
Katie
Jacob
David

Updated on: 10-Dec-2019

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements