Copying the Collection elements to an array in C#



To copy the Collection elements to an array, the code is as follows −

Example

 Live Demo

using System; using System.Collections.ObjectModel; public class Demo {    public static void Main(){       Collection<string> col = new Collection<string>();       col.Add("One");       col.Add("Two");       col.Add("Three");       col.Add("Four");       col.Add("Five");       col.Add("Six");       col.Add("Seven");       col.Add("Eight");       Console.WriteLine("Collection....");       foreach(string str in col){          Console.WriteLine(str);       }       string[] strArr = new string[10];       col.CopyTo(strArr, 2);       Console.WriteLine("
Array...");       foreach(string str in strArr){          Console.WriteLine(str);       }    } }

Output

This will produce the following output −

Collection.... One Two Three Four Five Six Seven Eight Array... One Two Three Four Five Six Seven Eight

Example

Let us now see another example −

 Live Demo

using System; using System.Collections.ObjectModel; public class Demo {    public static void Main(){       Collection<string> col = new Collection<string>();       col.Add("One");       col.Add("Two");       col.Add("Three");       col.Add("Four");       col.Add("Five");       Console.WriteLine("Collection....");       foreach(string str in col){          Console.WriteLine(str);       }       string[] strArr = new string[10];       col.CopyTo(strArr, 3);       Console.WriteLine("
Array...");       foreach(string str in strArr){          Console.WriteLine(str);       }    } }

Output

This will produce the following output −

Collection.... One Two Three Four Five Array... One Two Three Four Five
Updated on: 2019-12-10T10:45:09+05:30

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements